file_id
stringlengths 5
10
| content
stringlengths 57
33.1k
| repo
stringlengths 8
77
| path
stringlengths 6
174
| token_length
int64 19
8.19k
| original_comment
stringlengths 7
10.6k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 21
33.1k
|
---|---|---|---|---|---|---|---|---|
442_8 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| google/guava | guava/src/com/google/common/collect/TreeRangeMap.java | 7,822 | // we know ( [ ) | line_comment | pl | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know <SUF>
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
|
442_12 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| google/guava | guava/src/com/google/common/collect/TreeRangeMap.java | 7,822 | // we know ( ] | line_comment | pl | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know <SUF>
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
|
442_14 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| google/guava | guava/src/com/google/common/collect/TreeRangeMap.java | 7,822 | // we know [ ( ] ) | line_comment | pl | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know <SUF>
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
|
442_16 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| google/guava | guava/src/com/google/common/collect/TreeRangeMap.java | 7,822 | // we know ( | | line_comment | pl | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know <SUF>
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
|
442_17 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know ( | )
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| google/guava | guava/src/com/google/common/collect/TreeRangeMap.java | 7,822 | // we know ( | ) | line_comment | pl | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiFunction;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
private void split(Cut<K> cut) {
/*
* The comments for this method will use | to indicate the cut point and ( ) to indicate the
* bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryToSplit = entriesByLowerBound.lowerEntry(cut);
if (mapEntryToSplit == null) {
return;
}
// we know ( |
RangeMapEntry<K, V> rangeMapEntry = mapEntryToSplit.getValue();
if (rangeMapEntry.getUpperBound().compareTo(cut) <= 0) {
return;
}
// we know <SUF>
putRangeMapEntry(rangeMapEntry.getLowerBound(), cut, rangeMapEntry.getValue());
putRangeMapEntry(cut, rangeMapEntry.getUpperBound(), rangeMapEntry.getValue());
}
/**
* @since 28.1
*/
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkNotNull(range);
checkNotNull(remappingFunction);
if (range.isEmpty()) {
return;
}
split(range.lowerBound);
split(range.upperBound);
// Due to the splitting of any entries spanning the range bounds, we know that any entry with a
// lower bound in the merge range is entirely contained by the merge range.
Set<Entry<Cut<K>, RangeMapEntry<K, V>>> entriesInMergeRange =
entriesByLowerBound.subMap(range.lowerBound, range.upperBound).entrySet();
// Create entries mapping any unmapped ranges in the merge range to the specified value.
ImmutableMap.Builder<Cut<K>, RangeMapEntry<K, V>> gaps = ImmutableMap.builder();
if (value != null) {
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr =
entriesInMergeRange.iterator();
Cut<K> lowerBound = range.lowerBound;
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next().getValue();
Cut<K> upperBound = entry.getLowerBound();
if (!lowerBound.equals(upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
lowerBound = entry.getUpperBound();
}
if (!lowerBound.equals(range.upperBound)) {
gaps.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, range.upperBound, value));
}
}
// Remap all existing entries in the merge range.
final Iterator<Entry<Cut<K>, RangeMapEntry<K, V>>> backingItr = entriesInMergeRange.iterator();
while (backingItr.hasNext()) {
Entry<Cut<K>, RangeMapEntry<K, V>> entry = backingItr.next();
V newValue = remappingFunction.apply(entry.getValue().getValue(), value);
if (newValue == null) {
backingItr.remove();
} else {
entry.setValue(
new RangeMapEntry<K, V>(
entry.getValue().getLowerBound(), entry.getValue().getUpperBound(), newValue));
}
}
entriesByLowerBound.putAll(gaps.build());
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
// https://github.com/jspecify/jspecify-reference-checker/issues/162
@SuppressWarnings("nullness")
public void merge(
Range<Comparable<?>> range,
@CheckForNull Object value,
BiFunction<? super Object, ? super @Nullable Object, ? extends @Nullable Object>
remappingFunction) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot merge range " + range + " into an empty subRangeMap");
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public void merge(
Range<K> range,
@CheckForNull V value,
BiFunction<? super V, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
checkArgument(
subRange.encloses(range),
"Cannot merge range %s into a subRangeMap(%s)",
range,
subRange);
TreeRangeMap.this.merge(range, value, remappingFunction);
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
|
603_0 | package me.webace.w7.student;
import jakarta.persistence.*;
import java.time.LocalDate;
import java.time.Period;
@Entity //dla Hibernate
@Table //dla JPA, żeby wiedziało, że to Tabela
public class Student
{
@Id
@SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize = 1
)
@GeneratedValue (
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
private Long id;
private String name;
private String email;
private LocalDate dob;
@Transient
private Integer age;
public Student() {
}
public Student(Long id, String name, String email, LocalDate dob) {
this.id = id;
this.name = name;
this.email = email;
this.dob = dob;
}
public Student(String name, String email, LocalDate dob) {
this.name = name;
this.email = email;
this.dob = dob;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return Period.between(this.dob, LocalDate.now()).getYears();
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", dob=" + dob +
", age=" + age +
'}';
}
}
| WebAce-Group/java101-edycja1 | w7/Student.java | 621 | //dla JPA, żeby wiedziało, że to Tabela
| line_comment | pl | package me.webace.w7.student;
import jakarta.persistence.*;
import java.time.LocalDate;
import java.time.Period;
@Entity //dla Hibernate
@Table //dla JPA, <SUF>
public class Student
{
@Id
@SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize = 1
)
@GeneratedValue (
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
private Long id;
private String name;
private String email;
private LocalDate dob;
@Transient
private Integer age;
public Student() {
}
public Student(Long id, String name, String email, LocalDate dob) {
this.id = id;
this.name = name;
this.email = email;
this.dob = dob;
}
public Student(String name, String email, LocalDate dob) {
this.name = name;
this.email = email;
this.dob = dob;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
public Integer getAge() {
return Period.between(this.dob, LocalDate.now()).getYears();
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", dob=" + dob +
", age=" + age +
'}';
}
}
|
606_0 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | // Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania <SUF>
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
|
606_1 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | //studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w <SUF>
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
|
606_2 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | //elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, <SUF>
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
|
606_3 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | //wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych <SUF>
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
|
606_4 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | //aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca <SUF>
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
|
606_5 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | //zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została <SUF>
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
|
606_6 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | //niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać <SUF>
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
|
606_7 | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
//jednostkowych.
}
}
| Ch3shireDev/WIT-Zajecia | semestr-6/Java/kolokwium1/Main.java | 308 | //ale można dodawać nowe. Rezultat zadania trzeba pokazać za pomocą testów
| line_comment | pl | package kolokwium1;
public class Main {
public static void main(String[] args) {
// Do wykonania jest program, który umożliwi przechowywanie i przetwarzanie danych
//studentów w poszczególnych grupach studenckich. Program będzie pewnego rodzaju
//elektronicznym dziennikiem, umożliwiającym ewidencję studentów w danej grupie oraz
//wpisywanie danych o liczbie zdobytych punktów w ramach następujących kryteriów:
//aktywność, praca domowa, projekt, kolokwium 1, kolokwium 2, egzamin. Do wykonania
//zadania została udostępniona hierarchia dziedziczenia klas którą należy użyć. Nie można w
//niej zmieniać zadeklarowanych elementów (chyba że jest to jawnie podane w poleceniu),
//ale można <SUF>
//jednostkowych.
}
}
|
609_0 | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
// funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
// pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
// algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} | dawidolko/Programming-Java | Lab02/Zadanie2.java | 1,317 | // Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
| line_comment | pl | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator <SUF>
// funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
// pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
// algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} |
609_1 | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
// funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
// pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
// algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} | dawidolko/Programming-Java | Lab02/Zadanie2.java | 1,317 | // funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
| line_comment | pl | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
// funkcji trygonometrycznych <SUF>
// pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
// algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} |
609_2 | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
// funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
// pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
// algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} | dawidolko/Programming-Java | Lab02/Zadanie2.java | 1,317 | // pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
| line_comment | pl | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
// funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
// pamiętać, że <SUF>
// algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} |
609_3 | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
// funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
// pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
// algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} | dawidolko/Programming-Java | Lab02/Zadanie2.java | 1,317 | // algorytmów wyświetlaj na konsoli. Do obsługi menu proszę użyć konstrukcji switch-case oraz pętli
| line_comment | pl | import java.util.Scanner;
//Zadanie 2.
// Napisz kalkulator obliczający: sumę, różnicę, iloczyn, iloraz, potęgę, pierwiastek, oraz wartości
// funkcji trygonometrycznych dla zadanego kąta. Użyj biblioteki Math np. Math. Sin(2.5). Proszę
// pamiętać, że wartości kąta podawane do funkcji mierzone są miarą łukową. Wyniki działania
// algorytmów wyświetlaj <SUF>
// while.
public class Zadanie2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("Wybierz opcję:");
System.out.println("1 - Dodawanie");
System.out.println("2 - Odejmowanie");
System.out.println("3 - Mnożenie");
System.out.println("4 - Dzielenie");
System.out.println("5 - Potęga");
System.out.println("6 - Pierwiastek");
System.out.println("7 - Sinus");
System.out.println("8 - Cosinus");
System.out.println("9 - Tangens");
System.out.println("0 - Wyjście");
System.out.print("Wybrałeś: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Podaj pierwszą liczbę:");
double a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
double b = scanner.nextDouble();
double sum = a + b;
System.out.println("Suma wynosi: " + sum);
break;
case 2:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double diff = a - b;
System.out.println("Różnica wynosi: " + diff);
break;
case 3:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double prod = a * b;
System.out.println("Iloczyn wynosi: " + prod);
break;
case 4:
System.out.println("Podaj pierwszą liczbę:");
a = scanner.nextDouble();
System.out.println("Podaj drugą liczbę:");
b = scanner.nextDouble();
double quotient = a / b;
System.out.println("Iloraz wynosi: " + quotient);
break;
case 5:
System.out.println("Podaj podstawę:");
a = scanner.nextDouble();
System.out.println("Podaj wykładnik:");
b = scanner.nextDouble();
double pow = Math.pow(a, b);
System.out.println("Wynik wynosi: " + pow);
break;
case 6:
System.out.println("Podaj liczbę:");
a = scanner.nextDouble();
double sqrt = Math.sqrt(a);
System.out.println("Pierwiastek wynosi: " + sqrt);
break;
case 7:
System.out.println("Podaj kąt w radianach:");
double angle = scanner.nextDouble();
double sin = Math.sin(angle);
System.out.println("Sinus wynosi: " + sin);
break;
case 8:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double cos = Math.cos(angle);
System.out.println("Cosinus wynosi: " + cos);
break;
case 9:
System.out.println("Podaj kąt w radianach:");
angle = scanner.nextDouble();
double tan = Math.tan(angle);
System.out.println("Tangens wynosi: " + tan);
break;
case 0:
System.out.println("Zakończyłeś program!");
exit = true;
break;
default:
System.out.println("Nieprawidłowa opcja!");
break;
}
}
}
} |
610_2 | package model;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
@XmlRootElement
public class Player extends MovingObject{
private String nick;
private String team;
@JsonIgnore
private boolean isShot = false;
//private double xPosition, yPosition;
//private double xDirection, yDirection;
//Możliwe że Player powinien rozszerzać MovingObject, ale wtedy w tym konstruktorze
//musiałyby być też przemieszczenia x i y łodzi
public Player(String nick, String team, double xPosition, double yPosition, double xDirection, double yDirection) {
super(xPosition, yPosition, xDirection, yDirection, 30.0d);
this.nick = nick;
this.team = team;
//this.xPosition = xPosition;
//this.yPosition = yPosition;
//this.xDirection = xDirection; //randomV();
//this.yDirection = yDirection; //randomV();
}
/*private double randomV() {
return Math.random()*10.0-5.0;
}*/
@JsonProperty("x")
public double getxPosition() {
return this.x;
}
public void setxPosition(double xPosition) {
this.x = xPosition;
}
@JsonProperty("y")
public double getyPosition() {
return y;
}
public void setyPosition(double yPosition) {
this.y = yPosition;
}
@JsonProperty("xDirection")
public double getxDirection() {
return this.deltaX;
}
public void setxDirection(double xDirection) {
this.deltaX = xDirection;
}
@JsonProperty("yDirection")
public double getyDirection() {
return this.deltaY;
}
@JsonIgnore
public void setyDirection(double yDirection) {
this.deltaY = yDirection;
}
@JsonProperty("user_nick")
public String getNick() {
return nick;
}
@JsonProperty("team")
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
@Override
public String toString(){
return "name:"+nick+" team:"+team;
}
@JsonProperty("is_shot")
public boolean getIsShot(){
return isShot;
}
public void shot() {
isShot = true;
}
}
| tloszabno/RedOctober | app/model/Player.java | 730 | //Możliwe że Player powinien rozszerzać MovingObject, ale wtedy w tym konstruktorze | line_comment | pl | package model;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
@XmlRootElement
public class Player extends MovingObject{
private String nick;
private String team;
@JsonIgnore
private boolean isShot = false;
//private double xPosition, yPosition;
//private double xDirection, yDirection;
//Możliwe że <SUF>
//musiałyby być też przemieszczenia x i y łodzi
public Player(String nick, String team, double xPosition, double yPosition, double xDirection, double yDirection) {
super(xPosition, yPosition, xDirection, yDirection, 30.0d);
this.nick = nick;
this.team = team;
//this.xPosition = xPosition;
//this.yPosition = yPosition;
//this.xDirection = xDirection; //randomV();
//this.yDirection = yDirection; //randomV();
}
/*private double randomV() {
return Math.random()*10.0-5.0;
}*/
@JsonProperty("x")
public double getxPosition() {
return this.x;
}
public void setxPosition(double xPosition) {
this.x = xPosition;
}
@JsonProperty("y")
public double getyPosition() {
return y;
}
public void setyPosition(double yPosition) {
this.y = yPosition;
}
@JsonProperty("xDirection")
public double getxDirection() {
return this.deltaX;
}
public void setxDirection(double xDirection) {
this.deltaX = xDirection;
}
@JsonProperty("yDirection")
public double getyDirection() {
return this.deltaY;
}
@JsonIgnore
public void setyDirection(double yDirection) {
this.deltaY = yDirection;
}
@JsonProperty("user_nick")
public String getNick() {
return nick;
}
@JsonProperty("team")
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
@Override
public String toString(){
return "name:"+nick+" team:"+team;
}
@JsonProperty("is_shot")
public boolean getIsShot(){
return isShot;
}
public void shot() {
isShot = true;
}
}
|
610_3 | package model;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
@XmlRootElement
public class Player extends MovingObject{
private String nick;
private String team;
@JsonIgnore
private boolean isShot = false;
//private double xPosition, yPosition;
//private double xDirection, yDirection;
//Możliwe że Player powinien rozszerzać MovingObject, ale wtedy w tym konstruktorze
//musiałyby być też przemieszczenia x i y łodzi
public Player(String nick, String team, double xPosition, double yPosition, double xDirection, double yDirection) {
super(xPosition, yPosition, xDirection, yDirection, 30.0d);
this.nick = nick;
this.team = team;
//this.xPosition = xPosition;
//this.yPosition = yPosition;
//this.xDirection = xDirection; //randomV();
//this.yDirection = yDirection; //randomV();
}
/*private double randomV() {
return Math.random()*10.0-5.0;
}*/
@JsonProperty("x")
public double getxPosition() {
return this.x;
}
public void setxPosition(double xPosition) {
this.x = xPosition;
}
@JsonProperty("y")
public double getyPosition() {
return y;
}
public void setyPosition(double yPosition) {
this.y = yPosition;
}
@JsonProperty("xDirection")
public double getxDirection() {
return this.deltaX;
}
public void setxDirection(double xDirection) {
this.deltaX = xDirection;
}
@JsonProperty("yDirection")
public double getyDirection() {
return this.deltaY;
}
@JsonIgnore
public void setyDirection(double yDirection) {
this.deltaY = yDirection;
}
@JsonProperty("user_nick")
public String getNick() {
return nick;
}
@JsonProperty("team")
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
@Override
public String toString(){
return "name:"+nick+" team:"+team;
}
@JsonProperty("is_shot")
public boolean getIsShot(){
return isShot;
}
public void shot() {
isShot = true;
}
}
| tloszabno/RedOctober | app/model/Player.java | 730 | //musiałyby być też przemieszczenia x i y łodzi | line_comment | pl | package model;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
@XmlRootElement
public class Player extends MovingObject{
private String nick;
private String team;
@JsonIgnore
private boolean isShot = false;
//private double xPosition, yPosition;
//private double xDirection, yDirection;
//Możliwe że Player powinien rozszerzać MovingObject, ale wtedy w tym konstruktorze
//musiałyby być <SUF>
public Player(String nick, String team, double xPosition, double yPosition, double xDirection, double yDirection) {
super(xPosition, yPosition, xDirection, yDirection, 30.0d);
this.nick = nick;
this.team = team;
//this.xPosition = xPosition;
//this.yPosition = yPosition;
//this.xDirection = xDirection; //randomV();
//this.yDirection = yDirection; //randomV();
}
/*private double randomV() {
return Math.random()*10.0-5.0;
}*/
@JsonProperty("x")
public double getxPosition() {
return this.x;
}
public void setxPosition(double xPosition) {
this.x = xPosition;
}
@JsonProperty("y")
public double getyPosition() {
return y;
}
public void setyPosition(double yPosition) {
this.y = yPosition;
}
@JsonProperty("xDirection")
public double getxDirection() {
return this.deltaX;
}
public void setxDirection(double xDirection) {
this.deltaX = xDirection;
}
@JsonProperty("yDirection")
public double getyDirection() {
return this.deltaY;
}
@JsonIgnore
public void setyDirection(double yDirection) {
this.deltaY = yDirection;
}
@JsonProperty("user_nick")
public String getNick() {
return nick;
}
@JsonProperty("team")
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
@Override
public String toString(){
return "name:"+nick+" team:"+team;
}
@JsonProperty("is_shot")
public boolean getIsShot(){
return isShot;
}
public void shot() {
isShot = true;
}
}
|
611_0 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | /*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/ | block_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki <SUF>*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_1 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //srebrny prostokat wyboru | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat <SUF>
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_2 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //wspolrzedne do wstawiania elementow | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do <SUF>
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_3 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //Kolory tekstu na przyciskach | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu <SUF>
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_4 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //Pozycja prostokąta wyboru save'a | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta <SUF>
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_5 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //Odświeżenie kolorów przycisków | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów <SUF>
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_6 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //Przewijanie prostokata do góry - klawisz, przycisk góra | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata <SUF>
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_7 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //Przewijanie prostokata do dołu - klawisz, przycisk dół | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata <SUF>
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_8 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //Ustalenie kolorów nr savów | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów <SUF>
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
611_9 | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta wyboru
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
| Kalwador/Java-2D-Game | LegendaryAdventure/src/states/LoadGameState.java | 2,502 | //Wyswietlanie prostokąta wyboru | line_comment | pl | package states;
import gameUtils.Fonts;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
/*
Może być taki problem że po zapisaniu gry, i wejściu do Load State nie będzie nowgo sava,
winą jest odświerzanie okna, należy zadbać aby po zapisaniu gry odświerzyć load state.
*/
public class LoadGameState extends BasicGameState {
Image backGround;
Image borderGold; //zlote ramki
Image checkBorderSilver; //srebrny prostokat wyboru
String mouse;
String onScreenLoc; //wspolrzedne do wstawiania elementow
gameUtils.Fonts fonts;
Color cw = Color.white;
Color co = Color.orange;
Color cSaves[] = {co, cw, cw}; //Kolory savów
Color cButtons[] = {cw, cw, cw}; //Kolory tekstu na przyciskach
static model.Save stdTab[] = new model.Save[3];
int actualBSposition = 1; //Pozycja prostokąta wyboru save'a
int counter = 0;
@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
backGround = new Image("graphic/menu/backgroundMainMenu.jpg");
borderGold = new Image("graphic/menu/LoadStateWoutBg.png");
checkBorderSilver = new Image("graphic/menu/LSC_SilverBorder.png");
mouse = "";
onScreenLoc = " ";
updateSlots();
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int xpos = Mouse.getX();
int ypos = Mouse.getY();
mouse = "x= " + xpos + " y=" + ypos;
onScreenLoc = "x= " + xpos + " y=" + Math.abs(720 - ypos);
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
sbg.enterState(1);
}
//Odświeżenie kolorów przycisków
for (int j = 0; j < cButtons.length; j++) {
cButtons[j] = Color.white;
}
for (int j = 0; j < cSaves.length; j++) {
cSaves[j] = Color.white;
}
//LOAD BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 460 && ypos < 517)) {
if (input.isMouseButtonDown(0)) {
if (!stdTab[actualBSposition - 1].getMiniaturePath().equals("brak")) {
gameUtils.TXTsave.loadSave(actualBSposition);
states.PlayState.needToMapUpdate = true;
sbg.enterState(1);
}
}
cButtons[0] = co;
if (input.isMouseButtonDown(0)) {
cButtons[0] = Color.gray;
}
}
//DELETE BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 344 && ypos < 402)) {
if (input.isMouseButtonDown(0)) {
gameUtils.TXTsave.deleteSave(actualBSposition);
updateSlots();
sbg.enterState(11);
}
cButtons[1] = co;
if (input.isMouseButtonDown(0)) {
cButtons[1] = Color.gray;
}
}
//BACK BUTTON
if ((xpos > 262 && xpos < 471) && (ypos > 231 && ypos < 289)) {
if (input.isMouseButtonDown(0)) {
sbg.enterState(0);
}
cButtons[2] = co;
if (input.isMouseButtonDown(0)) {
cButtons[2] = Color.gray;
}
}
//Prostokąt 1
if ((xpos > 625 && xpos < 1130) && (ypos > 442 && ypos < 545)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 1;
}
}
//Prostokąt 2
if ((xpos > 625 && xpos < 1130) && (ypos > 327 && ypos < 433)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 2;
}
}
//Prostokąt 3
if ((xpos > 625 && xpos < 1130) && (ypos > 215 && ypos < 320)) {
if (input.isMouseButtonDown(0)) {
actualBSposition = 3;
}
}
//Przewijanie prostokata do góry - klawisz, przycisk góra
if (input.isKeyPressed(Input.KEY_UP)) {
if (actualBSposition > 1) {
actualBSposition--;
}
}
//Przewijanie prostokata do dołu - klawisz, przycisk dół
if (input.isKeyPressed(Input.KEY_DOWN)) {
if (actualBSposition < 3) {
actualBSposition++;
}
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.drawImage(backGround, 0, 0);
//złote ramki
g.drawImage(borderGold, 0, 0);
Fonts.print28().drawString(325, 218, "LOAD", cButtons[0]);
Fonts.print28().drawString(310, 335, "DELETE", cButtons[1]);
Fonts.print28().drawString(325, 448, "BACK", cButtons[2]);
//Ustalenie kolorów nr savów
switch (actualBSposition) {
case 1:
cSaves[0] = co;
cSaves[1] = cw;
break;
case 2:
cSaves[0] = cw;
cSaves[1] = co;
cSaves[2] = cw;
break;
case 3:
cSaves[1] = cw;
cSaves[2] = co;
break;
}
//Wyświetlanie savów
Fonts.print18().drawString(784, 192, stdTab[0].getMapLocation());
Fonts.print18().drawString(784, 252, stdTab[0].getSaveDate());
if (!stdTab[0].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[0].getMiniaturePath()), 630, 178);
}
Fonts.print18().drawString(784, 313, stdTab[1].getMapLocation());
Fonts.print18().drawString(784, 368, stdTab[1].getSaveDate());
if (!stdTab[1].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[1].getMiniaturePath()), 630, 289);
}
Fonts.print18().drawString(784, 414, stdTab[2].getMapLocation());
Fonts.print18().drawString(784, 474, stdTab[2].getSaveDate());
if (!stdTab[2].getMiniaturePath().equals("brak")) {
g.drawImage(new Image(stdTab[2].getMiniaturePath()), 630, 400);
}
//Wyswietlanie prostokąta <SUF>
switch (actualBSposition) {
case 1:
g.drawImage(checkBorderSilver, 623, 171);
break;
case 2:
g.drawImage(checkBorderSilver, 623, 286);
break;
case 3:
g.drawImage(checkBorderSilver, 623, 399);
break;
}
}
public LoadGameState(int state) {
}
@Override
public int getID() {
return 11;
}
public static void updateSlots() {
stdTab[0] = gameUtils.TXTsave.loadData(1);
stdTab[1] = gameUtils.TXTsave.loadData(2);
stdTab[2] = gameUtils.TXTsave.loadData(3);
}
}
|
614_0 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | /* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/ | block_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark <SUF>*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_2 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala <SUF>
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_3 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - <SUF>
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_4 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić <SUF>
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_5 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny" | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta <SUF>
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_6 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej, | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - <SUF>
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_7 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //ale zasadniczo te dwie metody służą do różnych rzeczy | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo <SUF>
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_8 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla <SUF>
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_9 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak <SUF>
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
614_10 | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
| Cyvil/KCKProjekt | src/Landmark.java | 2,203 | //Zwracamy któryś z promieni - jezeli jest true to zwracamy promien kolizji, jesli false - promien widoczności | line_comment | pl | import java.awt.Image;
import java.awt.Toolkit;
import java.lang.Math;
import java.util.Random;
public class Landmark {
/* stworzenie klasy Landmark o polach: position, type i colour;
* każdy Landmark ustawiany przez nas na mapie posiadał więc będzie trzy cechy:
* typ - rodzaj przedmiotu,budynku,miejsca itp.
* kolor landmarka w danym typie, poszerza gamę dostępnych w puli generatora landmarków
* pozycję - na bazie obiektu typu Point, wyznaczać będzie miejsce na mapie, w którym dany landmark zostanie umieszczony;
*
* wywołanie konstruktora bezargumentowego skutkuje postawieniem landmarka w formie szarego kamienia w punkcie Point=(50,50);
* wywołanie konstruktora trójargumentowego generuje losowy landmark:
* -oblicza modulo 9 z podanej na wejściu liczby, uzyskując liczbę typu integer, której na stałe odpowiada dany typ landmarku
* -oblicza modulo 10 z kolejnej podanej na wejściu liczby, której na stałe przypisane zostały kolory z dostępnej gamy
* -ustawia wartości x i y Punktu, który będzie wskazywał miejsce umieszczenia landmarka
*/
protected enum Type
{
STONE, TREE, SANTA, WINDMILL, CHURCH, HOUSE, SIGN, STATUE, CAT, BICYCLE, CROSS, DOG, BENCH, FLOWER, FONT, MAN, BALL, BIRD, CAR, BUSH
}
private Type type;
private Point position;
private double visibilityRadius;
private double collisionRadius;
/* private enum Colour
{
WHITE, YELLOW, ORANGE, GREEN, BLUE, PURPLE, RED, BROWN, BLACK, GREY,
}
*/
// Colour colour;
Landmark()
{
position = new Point(50,50);
type = Type.STONE;
visibilityRadius = 10.0;
collisionRadius = visibilityRadius/2.5;
}
//Konstruktor, ustala typ a tak�e przypisan� do niego widoczno�� Landmarku
Landmark(int t, Point p)
{
Random generator = new Random();
t = generator.nextInt(21);
switch(t){
case 0:
type = Type.STONE;
collisionRadius = 2.50;
break;
case 1:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 2:
type = Type.SANTA;
collisionRadius = 2.50;
break;
case 3:
type = Type.TREE;
collisionRadius = 2.5;
break;
case 4:
type = Type.WINDMILL;
collisionRadius = 3.0;
break;
case 5:
type = Type.CHURCH;
collisionRadius = 3.0;
break;
case 6:
type = Type.HOUSE;
collisionRadius = 3.00;
break;
case 7:
type = Type.SIGN;
collisionRadius = 2.50;
break;
case 8:
type = Type.STATUE;
collisionRadius = 2.50;
break;
case 9:
type = Type.CAT;
collisionRadius = 2.50;
break;
case 10:
type = Type.BICYCLE;
collisionRadius = 2.50;
break;
case 11:
type = Type.CROSS;
collisionRadius = 2.50;
break;
case 12:
type = Type.DOG;
collisionRadius = 2.50;
break;
case 13:
type = Type.FONT;
collisionRadius = 2.50;
break;
case 14:
type = Type.MAN;
collisionRadius = 2.50;
break;
case 15:
type = Type.BALL;
collisionRadius = 2.50;
break;
case 16:
type = Type.FLOWER;
collisionRadius = 2.50;
break;
case 17:
type = Type.BIRD;
collisionRadius = 2.50;
break;
case 18:
type = Type.CAR;
collisionRadius = 2.50;
break;
case 19:
type = Type.BUSH;
collisionRadius = 2.50;
break;
case 20:
type = Type.BENCH;
collisionRadius = 2.50;
break;
}
visibilityRadius = collisionRadius*3;
position = new Point();
position.setX(p.getX());
position.setY(p.getY());
}
//Widoczność - dla uproszczenia i realizmu zawsze jest jakby kołem wokół tego obiektu o promieniu visibilityRadius
//Żeby sprawdzić czy obiekt jest widoczny sprawdzamy jego odległość od punktu w którym stoimy
//Jeżeli ta odległość jest mniejsza niż promień widoczności to wtedy obiekt jest "widoczny"
boolean visibility(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= visibilityRadius)
return true;
else return false;
}
//Kolizja - tutaj sprawa ma się analogicznie, w istocie to tylko kopiuj wklej,
//ale zasadniczo te dwie metody służą do różnych rzeczy
//Tutaj dla UPROSZCZENIA przyjmujemy, że to obiekty kołowe, żeby nie musieć kombinować z kolizjami
//Generalnie tak dla ułatwienia przyjąłem, że promien kolizji jest 10 razy mniejszy od promienia widocznosci
boolean collision(Point p)
{
double distance = Math.sqrt((position.getX() - p.getX())*(position.getX() - p.getX()) + (position.getY() - p.getY())*(position.getY() - p.getY()));
if (distance <= collisionRadius)
return true;
else return false;
}
//Zwracamy typ
Type getType()
{
return this.type;
}
//Zwracamy któryś <SUF>
double getRadius(boolean collision)
{
if (collision) return collisionRadius;
else return visibilityRadius;
}
Point getPoint()
{
return position;
}
}
|
616_0 | package gui;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
class FrameCapturingTask implements Runnable {
Camera cam;
public FrameCapturingTask(Camera cam) {
this.cam = cam;
}
@Override
public void run() {
try {
cam.startCapturing();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Przyjmijmy na razie, że to jest klasa, z której odpalana jest aplikacja.
public class Testing implements FrameObserver{
Camera cam;
CanvasFrame canvasFrame = new CanvasFrame("Some Title");
long currentMilis = 0;
long oldMilis = 0;
public static void main(String args[]) throws Exception {
Testing main = new Testing(new Camera(0));
main.test();
}
public Testing(Camera cam) throws Exception {
this.cam = cam;
this.cam.addListener(this);
canvasFrame.setCanvasSize(400, 400);
}
void test() {
FrameCapturingTask fct = new FrameCapturingTask(cam);
new Thread(fct).start();
}
@Override
public void update(IplImage frame) {
oldMilis = currentMilis;
currentMilis = System.currentTimeMillis();
System.out.println("Got frame! (it takes " + (currentMilis - oldMilis) + ")");
canvasFrame.showImage(frame);
}
}
| mloza/iop-project | src/gui/Testing.java | 471 | // Przyjmijmy na razie, że to jest klasa, z której odpalana jest aplikacja. | line_comment | pl | package gui;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
class FrameCapturingTask implements Runnable {
Camera cam;
public FrameCapturingTask(Camera cam) {
this.cam = cam;
}
@Override
public void run() {
try {
cam.startCapturing();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Przyjmijmy na <SUF>
public class Testing implements FrameObserver{
Camera cam;
CanvasFrame canvasFrame = new CanvasFrame("Some Title");
long currentMilis = 0;
long oldMilis = 0;
public static void main(String args[]) throws Exception {
Testing main = new Testing(new Camera(0));
main.test();
}
public Testing(Camera cam) throws Exception {
this.cam = cam;
this.cam.addListener(this);
canvasFrame.setCanvasSize(400, 400);
}
void test() {
FrameCapturingTask fct = new FrameCapturingTask(cam);
new Thread(fct).start();
}
@Override
public void update(IplImage frame) {
oldMilis = currentMilis;
currentMilis = System.currentTimeMillis();
System.out.println("Got frame! (it takes " + (currentMilis - oldMilis) + ")");
canvasFrame.showImage(frame);
}
}
|
618_0 | /*
*
* Somado (System Optymalizacji Małych Dostaw)
* Optymalizacja dostaw towarów, dane OSM, problem VRP
*
* Autor: Maciej Kawecki 2016 (praca inż. EE PW)
*
*/
package gui;
import datamodel.IData;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import datamodel.tablemodels.ITableModel;
/**
*
* Renderer do komórek tabeli zawierających pole stanu (do zmiany koloru tekstu)
*
* @author Maciej Kawecki
* @version 1.0
*
*/
@SuppressWarnings("serial")
public class TableStateCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
boolean noSelection = false;
int tmpRow = row;
try {
row = table.getRowSorter().convertRowIndexToModel(row);
}
// wyjątek oznacza że na tabela ma wyłączone zaznaczanie
catch (NullPointerException e) { noSelection = true; }
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, hasFocus, hasFocus, row, col);
ITableModel<? extends IData> tabModel = (ITableModel<?>) table.getModel();
if (tabModel.isStateColumn(col) && tabModel.getStateCellColor(row) != null) {
label.setForeground(tabModel.getStateCellColor(row));
if (!noSelection) {
if (table.getSelectedRow()==tmpRow) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
}
}
return label;
}
}
| makaw/somado | src/main/java/gui/TableStateCellRenderer.java | 529 | /*
*
* Somado (System Optymalizacji Małych Dostaw)
* Optymalizacja dostaw towarów, dane OSM, problem VRP
*
* Autor: Maciej Kawecki 2016 (praca inż. EE PW)
*
*/ | block_comment | pl | /*
*
* Somado (System Optymalizacji <SUF>*/
package gui;
import datamodel.IData;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import datamodel.tablemodels.ITableModel;
/**
*
* Renderer do komórek tabeli zawierających pole stanu (do zmiany koloru tekstu)
*
* @author Maciej Kawecki
* @version 1.0
*
*/
@SuppressWarnings("serial")
public class TableStateCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
boolean noSelection = false;
int tmpRow = row;
try {
row = table.getRowSorter().convertRowIndexToModel(row);
}
// wyjątek oznacza że na tabela ma wyłączone zaznaczanie
catch (NullPointerException e) { noSelection = true; }
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, hasFocus, hasFocus, row, col);
ITableModel<? extends IData> tabModel = (ITableModel<?>) table.getModel();
if (tabModel.isStateColumn(col) && tabModel.getStateCellColor(row) != null) {
label.setForeground(tabModel.getStateCellColor(row));
if (!noSelection) {
if (table.getSelectedRow()==tmpRow) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
}
}
return label;
}
}
|
618_1 | /*
*
* Somado (System Optymalizacji Małych Dostaw)
* Optymalizacja dostaw towarów, dane OSM, problem VRP
*
* Autor: Maciej Kawecki 2016 (praca inż. EE PW)
*
*/
package gui;
import datamodel.IData;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import datamodel.tablemodels.ITableModel;
/**
*
* Renderer do komórek tabeli zawierających pole stanu (do zmiany koloru tekstu)
*
* @author Maciej Kawecki
* @version 1.0
*
*/
@SuppressWarnings("serial")
public class TableStateCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
boolean noSelection = false;
int tmpRow = row;
try {
row = table.getRowSorter().convertRowIndexToModel(row);
}
// wyjątek oznacza że na tabela ma wyłączone zaznaczanie
catch (NullPointerException e) { noSelection = true; }
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, hasFocus, hasFocus, row, col);
ITableModel<? extends IData> tabModel = (ITableModel<?>) table.getModel();
if (tabModel.isStateColumn(col) && tabModel.getStateCellColor(row) != null) {
label.setForeground(tabModel.getStateCellColor(row));
if (!noSelection) {
if (table.getSelectedRow()==tmpRow) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
}
}
return label;
}
}
| makaw/somado | src/main/java/gui/TableStateCellRenderer.java | 529 | /**
*
* Renderer do komórek tabeli zawierających pole stanu (do zmiany koloru tekstu)
*
* @author Maciej Kawecki
* @version 1.0
*
*/ | block_comment | pl | /*
*
* Somado (System Optymalizacji Małych Dostaw)
* Optymalizacja dostaw towarów, dane OSM, problem VRP
*
* Autor: Maciej Kawecki 2016 (praca inż. EE PW)
*
*/
package gui;
import datamodel.IData;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import datamodel.tablemodels.ITableModel;
/**
*
* Renderer do komórek <SUF>*/
@SuppressWarnings("serial")
public class TableStateCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
boolean noSelection = false;
int tmpRow = row;
try {
row = table.getRowSorter().convertRowIndexToModel(row);
}
// wyjątek oznacza że na tabela ma wyłączone zaznaczanie
catch (NullPointerException e) { noSelection = true; }
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, hasFocus, hasFocus, row, col);
ITableModel<? extends IData> tabModel = (ITableModel<?>) table.getModel();
if (tabModel.isStateColumn(col) && tabModel.getStateCellColor(row) != null) {
label.setForeground(tabModel.getStateCellColor(row));
if (!noSelection) {
if (table.getSelectedRow()==tmpRow) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
}
}
return label;
}
}
|
618_2 | /*
*
* Somado (System Optymalizacji Małych Dostaw)
* Optymalizacja dostaw towarów, dane OSM, problem VRP
*
* Autor: Maciej Kawecki 2016 (praca inż. EE PW)
*
*/
package gui;
import datamodel.IData;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import datamodel.tablemodels.ITableModel;
/**
*
* Renderer do komórek tabeli zawierających pole stanu (do zmiany koloru tekstu)
*
* @author Maciej Kawecki
* @version 1.0
*
*/
@SuppressWarnings("serial")
public class TableStateCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
boolean noSelection = false;
int tmpRow = row;
try {
row = table.getRowSorter().convertRowIndexToModel(row);
}
// wyjątek oznacza że na tabela ma wyłączone zaznaczanie
catch (NullPointerException e) { noSelection = true; }
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, hasFocus, hasFocus, row, col);
ITableModel<? extends IData> tabModel = (ITableModel<?>) table.getModel();
if (tabModel.isStateColumn(col) && tabModel.getStateCellColor(row) != null) {
label.setForeground(tabModel.getStateCellColor(row));
if (!noSelection) {
if (table.getSelectedRow()==tmpRow) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
}
}
return label;
}
}
| makaw/somado | src/main/java/gui/TableStateCellRenderer.java | 529 | // wyjątek oznacza że na tabela ma wyłączone zaznaczanie | line_comment | pl | /*
*
* Somado (System Optymalizacji Małych Dostaw)
* Optymalizacja dostaw towarów, dane OSM, problem VRP
*
* Autor: Maciej Kawecki 2016 (praca inż. EE PW)
*
*/
package gui;
import datamodel.IData;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import datamodel.tablemodels.ITableModel;
/**
*
* Renderer do komórek tabeli zawierających pole stanu (do zmiany koloru tekstu)
*
* @author Maciej Kawecki
* @version 1.0
*
*/
@SuppressWarnings("serial")
public class TableStateCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
boolean noSelection = false;
int tmpRow = row;
try {
row = table.getRowSorter().convertRowIndexToModel(row);
}
// wyjątek oznacza <SUF>
catch (NullPointerException e) { noSelection = true; }
JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, hasFocus, hasFocus, row, col);
ITableModel<? extends IData> tabModel = (ITableModel<?>) table.getModel();
if (tabModel.isStateColumn(col) && tabModel.getStateCellColor(row) != null) {
label.setForeground(tabModel.getStateCellColor(row));
if (!noSelection) {
if (table.getSelectedRow()==tmpRow) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
}
}
return label;
}
}
|
619_9 | /* TagDifferenceSet.java created 2007-11-14
*
*/
package org.signalml.domain.tag;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;
import org.signalml.plugin.export.signal.SignalSelectionType;
import org.signalml.plugin.export.signal.Tag;
/**
* This class represents a set of {@link TagDifference differences} between
* {@link Tag tags}.
* Allows to find which differences are located between two points in time.
*
* @author Michal Dobaczewski © 2007-2008 CC Otwarte Systemy Komputerowe Sp. z o.o.
*/
public class TagDifferenceSet {
/**
* the actual set containing tag {@link TagDifference differences}
*/
private TreeSet<TagDifference> differences;
/**
* the length of the longest {@link TagDifference differences}
*/
private double maxDifferenceLength = 0;
/**
* Constructor. Creates an empty TagDifferenceSet.
*/
public TagDifferenceSet() {
differences = new TreeSet<TagDifference>();
}
/**
* Constructor. Creates a TagDifferenceSet with given
* {@link TagDifference differences}.
* @param differences the set of differences to be added
*/
public TagDifferenceSet(TreeSet<TagDifference> differences) {
this.differences = differences;
calculateMaxTagLength();
}
/**
* Returns the set containing {@link TagDifference tag differences}.
* @return the set containing tag differences
*/
public TreeSet<TagDifference> getDifferences() {
return differences;
}
/**
* Adds the given collection of {@link TagDifference tag differences}
* to this set.
* @param toAdd the collection of tag differences
*/
public void addDifferences(Collection<TagDifference> toAdd) {
differences.addAll(toAdd);
calculateMaxTagLength();
}
/**
* Returns the set of {@link TagDifference differences} for
* {@link Tag tagged selections} that start between
* <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive).
* @param start the starting position of the interval
* @param end the ending position of the interval
* @return the set of differences for tagged selections
* that start between <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive)
*/
//TODO czy to na pewno ma zwracać to co napisałem, wydawało mi się, że mają to być różnice przecinające się z przedziałem, ale tu mogą się załapać także znajdujące się przed nim (i krótsze od maksymalnego)
public SortedSet<TagDifference> getDifferencesBetween(double start, double end) {
TagDifference startMarker = new TagDifference(SignalSelectionType.CHANNEL, start-maxDifferenceLength, 0, null);
TagDifference endMarker = new TagDifference(SignalSelectionType.CHANNEL,end, Double.MAX_VALUE,null); // note that lengths matter, so that all tags starting at exactly end will be selected
return differences.subSet(startMarker, true, endMarker, true);
}
/**
* Calculates the maximal length of the difference in this set.
*/
private void calculateMaxTagLength() {
double maxDifferenceLength = 0;
for (TagDifference difference : differences) {
if (maxDifferenceLength < difference.getLength()) {
maxDifferenceLength = difference.getLength();
}
}
this.maxDifferenceLength = maxDifferenceLength;
}
}
| BrainTech/svarog | svarog/src/main/java/org/signalml/domain/tag/TagDifferenceSet.java | 1,020 | //TODO czy to na pewno ma zwracać to co napisałem, wydawało mi się, że mają to być różnice przecinające się z przedziałem, ale tu mogą się załapać także znajdujące się przed nim (i krótsze od maksymalnego) | line_comment | pl | /* TagDifferenceSet.java created 2007-11-14
*
*/
package org.signalml.domain.tag;
import java.util.Collection;
import java.util.SortedSet;
import java.util.TreeSet;
import org.signalml.plugin.export.signal.SignalSelectionType;
import org.signalml.plugin.export.signal.Tag;
/**
* This class represents a set of {@link TagDifference differences} between
* {@link Tag tags}.
* Allows to find which differences are located between two points in time.
*
* @author Michal Dobaczewski © 2007-2008 CC Otwarte Systemy Komputerowe Sp. z o.o.
*/
public class TagDifferenceSet {
/**
* the actual set containing tag {@link TagDifference differences}
*/
private TreeSet<TagDifference> differences;
/**
* the length of the longest {@link TagDifference differences}
*/
private double maxDifferenceLength = 0;
/**
* Constructor. Creates an empty TagDifferenceSet.
*/
public TagDifferenceSet() {
differences = new TreeSet<TagDifference>();
}
/**
* Constructor. Creates a TagDifferenceSet with given
* {@link TagDifference differences}.
* @param differences the set of differences to be added
*/
public TagDifferenceSet(TreeSet<TagDifference> differences) {
this.differences = differences;
calculateMaxTagLength();
}
/**
* Returns the set containing {@link TagDifference tag differences}.
* @return the set containing tag differences
*/
public TreeSet<TagDifference> getDifferences() {
return differences;
}
/**
* Adds the given collection of {@link TagDifference tag differences}
* to this set.
* @param toAdd the collection of tag differences
*/
public void addDifferences(Collection<TagDifference> toAdd) {
differences.addAll(toAdd);
calculateMaxTagLength();
}
/**
* Returns the set of {@link TagDifference differences} for
* {@link Tag tagged selections} that start between
* <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive).
* @param start the starting position of the interval
* @param end the ending position of the interval
* @return the set of differences for tagged selections
* that start between <code>start-maxDifferenceLength</code> (inclusive)
* and <code>end</code> (inclusive)
*/
//TODO czy <SUF>
public SortedSet<TagDifference> getDifferencesBetween(double start, double end) {
TagDifference startMarker = new TagDifference(SignalSelectionType.CHANNEL, start-maxDifferenceLength, 0, null);
TagDifference endMarker = new TagDifference(SignalSelectionType.CHANNEL,end, Double.MAX_VALUE,null); // note that lengths matter, so that all tags starting at exactly end will be selected
return differences.subSet(startMarker, true, endMarker, true);
}
/**
* Calculates the maximal length of the difference in this set.
*/
private void calculateMaxTagLength() {
double maxDifferenceLength = 0;
for (TagDifference difference : differences) {
if (maxDifferenceLength < difference.getLength()) {
maxDifferenceLength = difference.getLength();
}
}
this.maxDifferenceLength = maxDifferenceLength;
}
}
|
621_12 | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }, flags = { 0 })
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
// if (br.containsHTML("")) {
// throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
// }
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
final String filesize = br.getRegex(">Rozmiar:</div><div class=\"right\">([^<>\"]*?)</div>").getMatch(0);
if (filename == null || filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
link.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
/* Avoid chars which are not allowed in filenames under certain OS' */
private static String encodeUnicode(final String input) {
String output = input;
output = output.replace(":", ";");
output = output.replace("|", "¦");
output = output.replace("<", "[");
output = output.replace(">", "]");
output = output.replace("/", "⁄");
output = output.replace("\\", "∖");
output = output.replace("*", "#");
output = output.replace("?", "¿");
output = output.replace("!", "¡");
output = output.replace("\"", "'");
return output;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | svn2github/jdownloader | src/jd/plugins/hoster/PrzeklejOrg.java | 1,935 | //(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }, flags = { 0 })
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }, <SUF>
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
// if (br.containsHTML("")) {
// throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
// }
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
final String filesize = br.getRegex(">Rozmiar:</div><div class=\"right\">([^<>\"]*?)</div>").getMatch(0);
if (filename == null || filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
link.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
/* Avoid chars which are not allowed in filenames under certain OS' */
private static String encodeUnicode(final String input) {
String output = input;
output = output.replace(":", ";");
output = output.replace("|", "¦");
output = output.replace("<", "[");
output = output.replace(">", "]");
output = output.replace("/", "⁄");
output = output.replace("\\", "∖");
output = output.replace("*", "#");
output = output.replace("?", "¿");
output = output.replace("!", "¡");
output = output.replace("\"", "'");
return output;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} |
621_15 | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }, flags = { 0 })
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
// if (br.containsHTML("")) {
// throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
// }
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
final String filesize = br.getRegex(">Rozmiar:</div><div class=\"right\">([^<>\"]*?)</div>").getMatch(0);
if (filename == null || filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
link.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
/* Avoid chars which are not allowed in filenames under certain OS' */
private static String encodeUnicode(final String input) {
String output = input;
output = output.replace(":", ";");
output = output.replace("|", "¦");
output = output.replace("<", "[");
output = output.replace(">", "]");
output = output.replace("/", "⁄");
output = output.replace("\\", "∖");
output = output.replace("*", "#");
output = output.replace("?", "¿");
output = output.replace("!", "¡");
output = output.replace("\"", "'");
return output;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | svn2github/jdownloader | src/jd/plugins/hoster/PrzeklejOrg.java | 1,935 | //przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }, flags = { 0 })
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
// if (br.containsHTML("")) {
// throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
// }
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
final String filesize = br.getRegex(">Rozmiar:</div><div class=\"right\">([^<>\"]*?)</div>").getMatch(0);
if (filename == null || filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
link.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + <SUF>
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
/* Avoid chars which are not allowed in filenames under certain OS' */
private static String encodeUnicode(final String input) {
String output = input;
output = output.replace(":", ";");
output = output.replace("|", "¦");
output = output.replace("<", "[");
output = output.replace(">", "]");
output = output.replace("/", "⁄");
output = output.replace("\\", "∖");
output = output.replace("*", "#");
output = output.replace("?", "¿");
output = output.replace("!", "¡");
output = output.replace("\"", "'");
return output;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} |
625_1 | /*
* Copyright (C) 2019-2021 FratikB0T Contributors
*
* This program 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.
*
* This program 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 <https://www.gnu.org/licenses/>.
*/
package pl.fratik.fratikcoiny.libs.chinczyk;
import lombok.Getter;
import lombok.experimental.Delegate;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.fratik.core.tlumaczenia.Language;
import pl.fratik.core.tlumaczenia.Tlumaczenia;
import pl.fratik.core.util.StreamUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
// aka nie mam pojęcia czemu to istnieje
@Getter
public enum SpecialSkins implements ChinczykSkin {
SENKO(1, "anime hlep", "https://i.fratikbot.pl/TN2P7jb.png") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
return "Senko Bread";
}
},
PIOTR_GRYF(1<<1, "w tym memie chodzi o to że jebać pis", "https://i.fratikbot.pl/x61TPLN.png") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
return "Peter Griffin";
}
},
PAPAJ(1<<2/*137*/, "papiez2137", "https://i.fratikbot.pl/wwREWg8.png") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
return "Jan Paweł 2";
}
},
WEEB(1<<3, "uwu owo >.<", "https://i.fratikbot.pl/LmbUteC.jpg") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
//noinspection SpellCheckingInspection - celowe
return "Anime gril";
}
};
private final Logger logger = LoggerFactory.getLogger(SpecialSkins.class);
private final int flag;
private final String password;
private interface DelExc {
void serialize(OutputStream os) throws IOException;
Emoji getEmoji();
String getValue();
String getTranslated(Tlumaczenia t, Language l) throws IOException;
}
private final @Delegate(types = ChinczykSkin.class, excludes = DelExc.class) SpecialSkinImpl skin;
private URL url;
private SoftReference<BufferedImage> background;
public class SpecialSkinImpl extends SkinImpl {
public SpecialSkinImpl(ChinczykSkin skin) {
super(skin);
bgColor = null;
}
@Override
protected void drawBackground(Graphics g, int width, int height) {
if (!isAvailable()) throw new IllegalStateException("skin nie jest dostępny");
g.drawImage(getBackground(), 0, 0, width, height, null);
}
}
SpecialSkins(int flag, String password) {
this.flag = flag;
this.password = password;
this.skin = new SpecialSkinImpl(Chinczyk.DefaultSkins.DEFAULT);
}
SpecialSkins(int flag, String password, String bgImage) {
this(flag, password);
try {
url = new URL(bgImage);
} catch (Exception e) {
logger.error("Nieprawidłowy link!", e);
url = null;
}
}
SpecialSkins(int flag, String password, URL bgImage) {
this(flag, password);
url = bgImage;
}
private synchronized BufferedImage getBackground() {
if (background != null && background.get() != null) return background.get();
try {
BufferedImage image = ImageIO.read(url);
background = new SoftReference<>(image);
return image;
} catch (Exception e) {
logger.error("Nie udało się pobrać zdjęcia!", e);
background = null;
return null;
}
}
public boolean isAvailable() {
return getBackground() != null;
}
public static SpecialSkins fromRaw(long raw) {
for (SpecialSkins s : values()) if ((raw & s.flag) == s.flag) return s;
return null;
}
public static SpecialSkins fromPassword(String password) {
for (SpecialSkins s : values()) if (password.equals(s.getPassword())) return s;
return null;
}
@Override
public void serialize(OutputStream os) throws IOException {
os.write(1);
StreamUtil.writeString(os, SpecialSkins.class.getName());
StreamUtil.writeUnsignedInt(os, 8);
StreamUtil.writeLong(os, flag);
}
public static ChinczykSkin deserialize(InputStream is) throws IOException {
SpecialSkins s = fromRaw(StreamUtil.readLong(is));
if (s == null || !s.isAvailable()) throw new IOException("skin nie jest dostępny");
return s;
}
@Override
public String getValue() {
return name();
}
@Override
public Emoji getEmoji() {
return null;
}
}
| fratik/FratikB0T | fratikcoiny/src/main/java/pl/fratik/fratikcoiny/libs/chinczyk/SpecialSkins.java | 1,674 | // aka nie mam pojęcia czemu to istnieje | line_comment | pl | /*
* Copyright (C) 2019-2021 FratikB0T Contributors
*
* This program 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.
*
* This program 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 <https://www.gnu.org/licenses/>.
*/
package pl.fratik.fratikcoiny.libs.chinczyk;
import lombok.Getter;
import lombok.experimental.Delegate;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.fratik.core.tlumaczenia.Language;
import pl.fratik.core.tlumaczenia.Tlumaczenia;
import pl.fratik.core.util.StreamUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
// aka nie <SUF>
@Getter
public enum SpecialSkins implements ChinczykSkin {
SENKO(1, "anime hlep", "https://i.fratikbot.pl/TN2P7jb.png") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
return "Senko Bread";
}
},
PIOTR_GRYF(1<<1, "w tym memie chodzi o to że jebać pis", "https://i.fratikbot.pl/x61TPLN.png") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
return "Peter Griffin";
}
},
PAPAJ(1<<2/*137*/, "papiez2137", "https://i.fratikbot.pl/wwREWg8.png") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
return "Jan Paweł 2";
}
},
WEEB(1<<3, "uwu owo >.<", "https://i.fratikbot.pl/LmbUteC.jpg") {
@Override
public String getTranslated(Tlumaczenia t, Language l) {
//noinspection SpellCheckingInspection - celowe
return "Anime gril";
}
};
private final Logger logger = LoggerFactory.getLogger(SpecialSkins.class);
private final int flag;
private final String password;
private interface DelExc {
void serialize(OutputStream os) throws IOException;
Emoji getEmoji();
String getValue();
String getTranslated(Tlumaczenia t, Language l) throws IOException;
}
private final @Delegate(types = ChinczykSkin.class, excludes = DelExc.class) SpecialSkinImpl skin;
private URL url;
private SoftReference<BufferedImage> background;
public class SpecialSkinImpl extends SkinImpl {
public SpecialSkinImpl(ChinczykSkin skin) {
super(skin);
bgColor = null;
}
@Override
protected void drawBackground(Graphics g, int width, int height) {
if (!isAvailable()) throw new IllegalStateException("skin nie jest dostępny");
g.drawImage(getBackground(), 0, 0, width, height, null);
}
}
SpecialSkins(int flag, String password) {
this.flag = flag;
this.password = password;
this.skin = new SpecialSkinImpl(Chinczyk.DefaultSkins.DEFAULT);
}
SpecialSkins(int flag, String password, String bgImage) {
this(flag, password);
try {
url = new URL(bgImage);
} catch (Exception e) {
logger.error("Nieprawidłowy link!", e);
url = null;
}
}
SpecialSkins(int flag, String password, URL bgImage) {
this(flag, password);
url = bgImage;
}
private synchronized BufferedImage getBackground() {
if (background != null && background.get() != null) return background.get();
try {
BufferedImage image = ImageIO.read(url);
background = new SoftReference<>(image);
return image;
} catch (Exception e) {
logger.error("Nie udało się pobrać zdjęcia!", e);
background = null;
return null;
}
}
public boolean isAvailable() {
return getBackground() != null;
}
public static SpecialSkins fromRaw(long raw) {
for (SpecialSkins s : values()) if ((raw & s.flag) == s.flag) return s;
return null;
}
public static SpecialSkins fromPassword(String password) {
for (SpecialSkins s : values()) if (password.equals(s.getPassword())) return s;
return null;
}
@Override
public void serialize(OutputStream os) throws IOException {
os.write(1);
StreamUtil.writeString(os, SpecialSkins.class.getName());
StreamUtil.writeUnsignedInt(os, 8);
StreamUtil.writeLong(os, flag);
}
public static ChinczykSkin deserialize(InputStream is) throws IOException {
SpecialSkins s = fromRaw(StreamUtil.readLong(is));
if (s == null || !s.isAvailable()) throw new IOException("skin nie jest dostępny");
return s;
}
@Override
public String getValue() {
return name();
}
@Override
public Emoji getEmoji() {
return null;
}
}
|
627_12 | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" })
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
if (br.containsHTML("Wygląda na to, że wybrany plik został skasowany") || !this.br.containsHTML("class=\"fileData\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
String filesize = br.getRegex(">Rozmiar[\t\n\r ]*?:</div>[\t\n\r ]*?<div class=\"right\">([^<>\"]*?)<").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
final boolean captcha_needed = false;
if (captcha_needed) {
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
} else {
br.postPage("http://przeklej.org/file/captachaValidate", "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
}
final String ad_url = this.br.getRegex("Kliknij <a href=\"(http://[^<>\"]*?)\"").getMatch(0);
if (ad_url != null) {
this.br.getHeaders().put("Referer", ad_url);
this.br.getPage("/file/download/" + downloadkey);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest|Wygląda na to, że wybrany plik został skasowany z naszych serwerów")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | mchubby-3rdparty/jdownloader | src/jd/plugins/hoster/PrzeklejOrg.java | 2,039 | //(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }) | line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }) <SUF>
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
if (br.containsHTML("Wygląda na to, że wybrany plik został skasowany") || !this.br.containsHTML("class=\"fileData\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
String filesize = br.getRegex(">Rozmiar[\t\n\r ]*?:</div>[\t\n\r ]*?<div class=\"right\">([^<>\"]*?)<").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
final boolean captcha_needed = false;
if (captcha_needed) {
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
} else {
br.postPage("http://przeklej.org/file/captachaValidate", "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
}
final String ad_url = this.br.getRegex("Kliknij <a href=\"(http://[^<>\"]*?)\"").getMatch(0);
if (ad_url != null) {
this.br.getHeaders().put("Referer", ad_url);
this.br.getPage("/file/download/" + downloadkey);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest|Wygląda na to, że wybrany plik został skasowany z naszych serwerów")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} |
627_13 | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" })
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
if (br.containsHTML("Wygląda na to, że wybrany plik został skasowany") || !this.br.containsHTML("class=\"fileData\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
String filesize = br.getRegex(">Rozmiar[\t\n\r ]*?:</div>[\t\n\r ]*?<div class=\"right\">([^<>\"]*?)<").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
final boolean captcha_needed = false;
if (captcha_needed) {
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
} else {
br.postPage("http://przeklej.org/file/captachaValidate", "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
}
final String ad_url = this.br.getRegex("Kliknij <a href=\"(http://[^<>\"]*?)\"").getMatch(0);
if (ad_url != null) {
this.br.getHeaders().put("Referer", ad_url);
this.br.getPage("/file/download/" + downloadkey);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest|Wygląda na to, że wybrany plik został skasowany z naszych serwerów")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | mchubby-3rdparty/jdownloader | src/jd/plugins/hoster/PrzeklejOrg.java | 2,039 | //przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" })
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
if (br.containsHTML("Wygląda na to, że wybrany plik został skasowany") || !this.br.containsHTML("class=\"fileData\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
String filesize = br.getRegex(">Rozmiar[\t\n\r ]*?:</div>[\t\n\r ]*?<div class=\"right\">([^<>\"]*?)<").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
final boolean captcha_needed = false;
if (captcha_needed) {
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + <SUF>
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
} else {
br.postPage("http://przeklej.org/file/captachaValidate", "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
}
final String ad_url = this.br.getRegex("Kliknij <a href=\"(http://[^<>\"]*?)\"").getMatch(0);
if (ad_url != null) {
this.br.getHeaders().put("Referer", ad_url);
this.br.getPage("/file/download/" + downloadkey);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest|Wygląda na to, że wybrany plik został skasowany z naszych serwerów")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} |
628_6 | /***************************************************************************
* (C) Copyright 2003-2018 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.script;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import games.stendhal.common.Direction;
import games.stendhal.common.grammar.Grammar;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.engine.SingletonRepository;
import games.stendhal.server.core.engine.StendhalRPZone;
import games.stendhal.server.core.events.TurnListener;
import games.stendhal.server.core.events.TurnNotifier;
import games.stendhal.server.core.scripting.ScriptImpl;
import games.stendhal.server.core.scripting.ScriptingSandbox;
import games.stendhal.server.entity.npc.ChatAction;
import games.stendhal.server.entity.npc.ConversationStates;
import games.stendhal.server.entity.npc.EventRaiser;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.condition.AdminCondition;
import games.stendhal.server.entity.npc.condition.NotCondition;
import games.stendhal.server.entity.player.Player;
/**
* A herald which will tell news to citizens.
*
* @author yoriy
*/
public class Herald extends ScriptImpl {
// TODO: there is ability of using list of herald names,
// it will add to game more fun.
public final String HeraldName = "Patrick";
// after some thinking, i decided to not implement here
// news records to file.
private final Logger logger = Logger.getLogger(Herald.class);
private final int REQUIRED_ADMINLEVEL_INFO = 100;
private final int REQUIRED_ADMINLEVEL_SET = 1000;
private final TurnNotifier turnNotifier = TurnNotifier.get();
//private final String HaveNoTime = "Cześć. Mam pracę do zrobienia i nie mam czasu na rozmowę z tobą.";
private final String HiOldFriend = "Jesteś! Witaj mój stary przyjacielu. Miło cię widzieć.";
private final String TooScared = "Jesteś szalony. Nie mogę ci pomóc. Imperator za to zabije nas obu.";
private final String BadJoke = "Żart, tak? Lubię dowcipy, ale nie za dużo.";
private final String FeelBad = "Nie wiem co ze mną nie tak. Nie czuję się dobrze... przepraszam, ale nie mogę ci pomóc...";
private final String DontUnderstand = "Przepraszam, ale nie rozumiem ciebie";
private final String InfoOnly = "Sądzę, że mogę ci na tyle zaufać, aby przedstawić tobie moja aktualną listę ogłoszeń. ";
private final String WillHelp = "Oczywiście. Zrobię wszystko co chcesz."+
" Powiedz mi '#speech <czas przerw (sekundy)> <czas zakończenia (sekundy)> <tekst do ogłoszenia>'. " +
"Jeżeli chcesz usunąć jakieś aktualne ogłoszenia to "+
"powiedz mi '#remove <numer ogłoszenia>'. "+
"Możesz mnie też zapytać o aktualne ogłoszenia mówiąc '#info'.";
private final LinkedList<HeraldNews> heraldNews = new LinkedList<HeraldNews>();
/**
* class for herald announcements.
*/
private final static class HeraldNews {
private final String news;
private final int interval;
private final int limit;
private int counter;
private final int id;
private final HeraldListener tnl;
public String getNews(){
return(news);
}
public int getInterval(){
return(interval);
}
public int getLimit(){
return(limit);
}
public int getCounter(){
return(counter);
}
public int getid(){
return(id);
}
public HeraldListener getTNL(){
return(tnl);
}
public void setCounter(int count){
this.counter=count;
}
/**
* constructor for news
* @param news - text to speech
* @param interval - interval between speeches in seconds.
* @param limit - time limit in seconds.
* @param counter - counter of speeches
* @param tnl - listener object
* @param id - unique number to internal works with news.
*/
public HeraldNews(String news, int interval, int limit, int counter,
HeraldListener tnl, int id){
this.news=news;
this.interval=interval;
this.limit=limit;
this.counter=counter;
this.tnl=tnl;
this.id=id;
}
}
/**
* herald turn listener object.
*/
class HeraldListener implements TurnListener{
private final int id;
/**
* function invokes by TurnNotifier each time when herald have to speech.
*/
@Override
public void onTurnReached(int currentTurn) {
workWithCounters(id);
}
/**
* tnl constructor.
* @param i - id of news
*/
public HeraldListener(int i) {
id=i;
}
}
/**
* invokes by /script -load Herald.class,
* placing herald near calling admin.
*/
@Override
public void load(final Player admin, final List<String> args, final ScriptingSandbox sandbox) {
if (admin==null) {
logger.error("herald called by null admin", new Throwable());
} else {
if (sandbox.getZone(admin).collides(admin.getX()+1, admin.getY())) {
logger.info("Spot for placing herald is occupied.");
admin.sendPrivateText("Miejsce obok ciebie jest zajęte. Nie można przenieść tam herolda.");
return;
}
sandbox.setZone(admin.getZone());
sandbox.add(getHerald(sandbox.getZone(admin), admin.getX() + 1, admin.getY()));
}
}
/**
* function invokes by HeraldListener.onTurnReached each time when herald have to speech.
* @param id - ID for news in news list
*/
public void workWithCounters(int id) {
int index=-1;
for (int i=0; i<heraldNews.size(); i++){
if(heraldNews.get(i).getid()==id){
index=i;
}
}
if (index==-1) {
logger.info("workWithCounters: id not found. ");
}
try {
final int interval = heraldNews.get(index).getInterval();
final int limit = heraldNews.get(index).getLimit();
final String text = heraldNews.get(index).getNews();
int counter = heraldNews.get(index).getCounter();
HeraldListener tnl = heraldNews.get(index).getTNL();
final SpeakerNPC npc = SingletonRepository.getNPCList().get(HeraldName);
npc.say(text);
counter++;
turnNotifier.dontNotify(tnl);
if(interval*counter<limit){
heraldNews.get(index).setCounter(counter);
turnNotifier.notifyInSeconds(interval, tnl);
} else {
// it was last announce.
heraldNews.remove(index);
}
} catch (IndexOutOfBoundsException ioobe) {
logger.error("workWithCounters: index is out of bounds: "+Integer.toString(index)+
", size "+Integer.toString(heraldNews.size())+
", id "+Integer.toString(id),ioobe);
}
}
/**
* kind of herald constructor
* @param zone - zone to place herald
* @param x - x coord in zone
* @param y - y coord in zone
* @return herald NPC :-)
*/
private SpeakerNPC getHerald(StendhalRPZone zone, int x, int y) {
final SpeakerNPC npc = new SpeakerNPC(HeraldName) {
/**
* npc says his job list
*/
class ReadJobsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
int newssize = heraldNews.size();
if(newssize==0){
npc.say("Moja lista ogłoszeń jest pusta.");
return;
}
StringBuilder sb=new StringBuilder();
sb.append("Oto " + Grammar.isare(newssize) + " moich aktualnych ogłoszeń: ");
for(int i=0; i<newssize;i++){
// will add 1 to position numbers to show position 0 as 1.
logger.info("info: index "+Integer.toString(i));
try {
final int left = heraldNews.get(i).getLimit()/heraldNews.get(i).getInterval()-
heraldNews.get(i).getCounter();
sb.append(" #"+Integer.toString(i+1)+". (left "+
Integer.toString(left)+" times): "+
"#Every #"+Integer.toString(heraldNews.get(i).getInterval())+
" #seconds #to #"+Integer.toString(heraldNews.get(i).getLimit())+
" #seconds: \""+heraldNews.get(i).getNews()+"\"");
} catch (IndexOutOfBoundsException ioobe) {
logger.error("ReadNewsAction: size of heraldNews = "+
Integer.toString(newssize), ioobe);
}
if(i!=(newssize-1)){
sb.append("; ");
}
}
npc.say(sb.toString());
}
}
/**
* npc says his job list
*/
class ReadNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
int newssize = heraldNews.size();
if(newssize==0){
npc.say("Moja lista ogłoszeń jest pusta.");
return;
}
StringBuilder sb=new StringBuilder();
sb.append("Oto " + Grammar.isare(newssize) + " moich aktualnych ogłoszeń: ");
for(int i=0; i<newssize;i++){
// will add 1 to position numbers to show position 0 as 1.
logger.info("info: index "+Integer.toString(i));
try {
sb.append("\""+heraldNews.get(i).getNews()+"\"");
} catch (IndexOutOfBoundsException ioobe) {
logger.error("ReadNewsAction: size of heraldNews = "+
Integer.toString(newssize), ioobe);
}
if(i!=(newssize-1)){
sb.append("; ");
}
}
npc.say(sb.toString());
}
}
/**
* NPC adds new job to his job list.
*/
class WriteNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
String text = sentence.getOriginalText();
logger.info("Oryginalne zdanie: " + text);
final String[] starr = text.split(" ");
if(starr.length < 2){
npc.say("Zapomniałeś o czasie zakończenia. Jestem śmiertelnikiem i trochę stary. Wiesz o co chodzi.");
return;
}
try {
final int interval = Integer.parseInt(starr[1].trim());
final int limit = Integer.parseInt(starr[2].trim());
if(limit < interval){
npc.say("Nie mogę policzyć do "+Integer.toString(interval)+
" i "+Integer.toString(limit)+" jest mniejsza od " + Integer.toString(interval)+
". Powtórz proszę.");
return;
}
try {
text = text.substring(starr[0].length()).trim().
substring(starr[1].length()).trim().
substring(starr[2].length()).trim();
final String out="Interval: "+Integer.toString(interval)+", limit: "+
Integer.toString(limit)+", text: \""+text+"\"";
npc.say("Dobrze zapisałem sobie. "+out);
logger.info("Admin "+player.getName()+
" added announcement: " +out);
final HeraldListener tnl = new HeraldListener(heraldNews.size());
heraldNews.add(new HeraldNews(text, interval, limit, 0, tnl, heraldNews.size()));
turnNotifier.notifyInSeconds(interval,tnl);
} catch (IndexOutOfBoundsException ioobe) {
npc.say(FeelBad);
logger.error("WriteNewsAction: Error while parsing sentence "+sentence.toString(), ioobe);
}
} catch (NumberFormatException nfe) {
npc.say(DontUnderstand);
logger.info("Error while parsing numbers. Interval and limit is: "+"("+starr[0]+"), ("+starr[1]+")");
}
}
}
/**
* NPC removes one job from his job list.
*/
class RemoveNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
String text = sentence.getOriginalText();
final String[] starr = text.split(" ");
if(starr.length < 2){
npc.say("Powiedz mi numer ogłoszenia do usunięcia.");
return;
}
final String number = starr[1];
try {
final int i = Integer.parseInt(number)-1;
if (i < 0){
npc.say(BadJoke);
return;
}
if (heraldNews.size()==0) {
npc.say("Nie mam teraz ogłoszeń.");
return;
}
if(i>=(heraldNews.size())){
npc.say("Mam tylko "+ Integer.toString(heraldNews.size())+
" ogłoszeń w tym momencie.");
return;
}
logger.warn("Admin "+player.getName()+" removing announcement #"+
Integer.toString(i)+": interval "+
Integer.toString(heraldNews.get(i).getInterval())+", limit "+
Integer.toString(heraldNews.get(i).getLimit())+", text \""+
heraldNews.get(i).getNews()+"\"");
turnNotifier.dontNotify(heraldNews.get(i).getTNL());
heraldNews.remove(i);
npc.say("Dobrze już zapomniałem.");
} catch (NumberFormatException nfe) {
logger.error("RemoveNewsAction: cant remove "+number+" speech.", nfe);
npc.say(DontUnderstand);
}
}
}
/**
* npc removes all jobs from his job list
*/
class ClearNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
logger.info("ClearAllAction: Admin "+player.getName()+
" cleared announcement list.");
for (int i=0; i<heraldNews.size(); i++) {
turnNotifier.dontNotify(heraldNews.get(i).getTNL());
}
if(heraldNews.size()!=0){
npc.say("Ufff mam trochę czasu na odpoczynek. Słyszałem, że jest jakaś gra w mieście Semos?");
heraldNews.clear();
} else {
npc.say("Oh dziękuję za troskę, ale wszystko w porządku.");
}
}
}
/**
* Finite states machine logic for herald.
*/
@Override
public void createDialog() {
add(ConversationStates.IDLE,
Arrays.asList("hi", "hola", "hello", "heya", "cześć"),
new NotCondition(new AdminCondition(REQUIRED_ADMINLEVEL_INFO)),
ConversationStates.IDLE,
null, new ReadNewsAction());
add(ConversationStates.IDLE,
Arrays.asList("hi", "hola", "hello", "heya", "cześć"),
new AdminCondition(REQUIRED_ADMINLEVEL_INFO),
ConversationStates.ATTENDING,
HiOldFriend, null);
add(ConversationStates.ATTENDING,
Arrays.asList("help", "pomoc"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
WillHelp, null);
add(ConversationStates.ATTENDING,
Arrays.asList("speech", "remove", "usuń"),
new NotCondition(new AdminCondition(REQUIRED_ADMINLEVEL_SET)),
ConversationStates.ATTENDING,
TooScared, null);
add(ConversationStates.ATTENDING,
Arrays.asList("help", "pomoc"),
new NotCondition(new AdminCondition(REQUIRED_ADMINLEVEL_SET)),
ConversationStates.ATTENDING,
InfoOnly, new ReadJobsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("info", "list", "tasks", "news", "informacje", "zadania", "nowości"),
new AdminCondition(REQUIRED_ADMINLEVEL_INFO),
ConversationStates.ATTENDING,
null, new ReadJobsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("speech", "powiedz"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
null, new WriteNewsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("remove", "usuń"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
null, new RemoveNewsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("clear", "wyczyść"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
null, new ClearNewsAction());
addGoodbye();
}
};
zone.assignRPObjectID(npc);
npc.setEntityClass("heraldnpc");
npc.setPosition(x, y);
npc.initHP(100);
npc.setDirection(Direction.LEFT);
return(npc);
}
}
| KarajuSs/PolskaGRA | src/games/stendhal/server/script/Herald.java | 6,413 | //private final String HaveNoTime = "Cześć. Mam pracę do zrobienia i nie mam czasu na rozmowę z tobą."; | line_comment | pl | /***************************************************************************
* (C) Copyright 2003-2018 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.script;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import games.stendhal.common.Direction;
import games.stendhal.common.grammar.Grammar;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.engine.SingletonRepository;
import games.stendhal.server.core.engine.StendhalRPZone;
import games.stendhal.server.core.events.TurnListener;
import games.stendhal.server.core.events.TurnNotifier;
import games.stendhal.server.core.scripting.ScriptImpl;
import games.stendhal.server.core.scripting.ScriptingSandbox;
import games.stendhal.server.entity.npc.ChatAction;
import games.stendhal.server.entity.npc.ConversationStates;
import games.stendhal.server.entity.npc.EventRaiser;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.condition.AdminCondition;
import games.stendhal.server.entity.npc.condition.NotCondition;
import games.stendhal.server.entity.player.Player;
/**
* A herald which will tell news to citizens.
*
* @author yoriy
*/
public class Herald extends ScriptImpl {
// TODO: there is ability of using list of herald names,
// it will add to game more fun.
public final String HeraldName = "Patrick";
// after some thinking, i decided to not implement here
// news records to file.
private final Logger logger = Logger.getLogger(Herald.class);
private final int REQUIRED_ADMINLEVEL_INFO = 100;
private final int REQUIRED_ADMINLEVEL_SET = 1000;
private final TurnNotifier turnNotifier = TurnNotifier.get();
//private final <SUF>
private final String HiOldFriend = "Jesteś! Witaj mój stary przyjacielu. Miło cię widzieć.";
private final String TooScared = "Jesteś szalony. Nie mogę ci pomóc. Imperator za to zabije nas obu.";
private final String BadJoke = "Żart, tak? Lubię dowcipy, ale nie za dużo.";
private final String FeelBad = "Nie wiem co ze mną nie tak. Nie czuję się dobrze... przepraszam, ale nie mogę ci pomóc...";
private final String DontUnderstand = "Przepraszam, ale nie rozumiem ciebie";
private final String InfoOnly = "Sądzę, że mogę ci na tyle zaufać, aby przedstawić tobie moja aktualną listę ogłoszeń. ";
private final String WillHelp = "Oczywiście. Zrobię wszystko co chcesz."+
" Powiedz mi '#speech <czas przerw (sekundy)> <czas zakończenia (sekundy)> <tekst do ogłoszenia>'. " +
"Jeżeli chcesz usunąć jakieś aktualne ogłoszenia to "+
"powiedz mi '#remove <numer ogłoszenia>'. "+
"Możesz mnie też zapytać o aktualne ogłoszenia mówiąc '#info'.";
private final LinkedList<HeraldNews> heraldNews = new LinkedList<HeraldNews>();
/**
* class for herald announcements.
*/
private final static class HeraldNews {
private final String news;
private final int interval;
private final int limit;
private int counter;
private final int id;
private final HeraldListener tnl;
public String getNews(){
return(news);
}
public int getInterval(){
return(interval);
}
public int getLimit(){
return(limit);
}
public int getCounter(){
return(counter);
}
public int getid(){
return(id);
}
public HeraldListener getTNL(){
return(tnl);
}
public void setCounter(int count){
this.counter=count;
}
/**
* constructor for news
* @param news - text to speech
* @param interval - interval between speeches in seconds.
* @param limit - time limit in seconds.
* @param counter - counter of speeches
* @param tnl - listener object
* @param id - unique number to internal works with news.
*/
public HeraldNews(String news, int interval, int limit, int counter,
HeraldListener tnl, int id){
this.news=news;
this.interval=interval;
this.limit=limit;
this.counter=counter;
this.tnl=tnl;
this.id=id;
}
}
/**
* herald turn listener object.
*/
class HeraldListener implements TurnListener{
private final int id;
/**
* function invokes by TurnNotifier each time when herald have to speech.
*/
@Override
public void onTurnReached(int currentTurn) {
workWithCounters(id);
}
/**
* tnl constructor.
* @param i - id of news
*/
public HeraldListener(int i) {
id=i;
}
}
/**
* invokes by /script -load Herald.class,
* placing herald near calling admin.
*/
@Override
public void load(final Player admin, final List<String> args, final ScriptingSandbox sandbox) {
if (admin==null) {
logger.error("herald called by null admin", new Throwable());
} else {
if (sandbox.getZone(admin).collides(admin.getX()+1, admin.getY())) {
logger.info("Spot for placing herald is occupied.");
admin.sendPrivateText("Miejsce obok ciebie jest zajęte. Nie można przenieść tam herolda.");
return;
}
sandbox.setZone(admin.getZone());
sandbox.add(getHerald(sandbox.getZone(admin), admin.getX() + 1, admin.getY()));
}
}
/**
* function invokes by HeraldListener.onTurnReached each time when herald have to speech.
* @param id - ID for news in news list
*/
public void workWithCounters(int id) {
int index=-1;
for (int i=0; i<heraldNews.size(); i++){
if(heraldNews.get(i).getid()==id){
index=i;
}
}
if (index==-1) {
logger.info("workWithCounters: id not found. ");
}
try {
final int interval = heraldNews.get(index).getInterval();
final int limit = heraldNews.get(index).getLimit();
final String text = heraldNews.get(index).getNews();
int counter = heraldNews.get(index).getCounter();
HeraldListener tnl = heraldNews.get(index).getTNL();
final SpeakerNPC npc = SingletonRepository.getNPCList().get(HeraldName);
npc.say(text);
counter++;
turnNotifier.dontNotify(tnl);
if(interval*counter<limit){
heraldNews.get(index).setCounter(counter);
turnNotifier.notifyInSeconds(interval, tnl);
} else {
// it was last announce.
heraldNews.remove(index);
}
} catch (IndexOutOfBoundsException ioobe) {
logger.error("workWithCounters: index is out of bounds: "+Integer.toString(index)+
", size "+Integer.toString(heraldNews.size())+
", id "+Integer.toString(id),ioobe);
}
}
/**
* kind of herald constructor
* @param zone - zone to place herald
* @param x - x coord in zone
* @param y - y coord in zone
* @return herald NPC :-)
*/
private SpeakerNPC getHerald(StendhalRPZone zone, int x, int y) {
final SpeakerNPC npc = new SpeakerNPC(HeraldName) {
/**
* npc says his job list
*/
class ReadJobsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
int newssize = heraldNews.size();
if(newssize==0){
npc.say("Moja lista ogłoszeń jest pusta.");
return;
}
StringBuilder sb=new StringBuilder();
sb.append("Oto " + Grammar.isare(newssize) + " moich aktualnych ogłoszeń: ");
for(int i=0; i<newssize;i++){
// will add 1 to position numbers to show position 0 as 1.
logger.info("info: index "+Integer.toString(i));
try {
final int left = heraldNews.get(i).getLimit()/heraldNews.get(i).getInterval()-
heraldNews.get(i).getCounter();
sb.append(" #"+Integer.toString(i+1)+". (left "+
Integer.toString(left)+" times): "+
"#Every #"+Integer.toString(heraldNews.get(i).getInterval())+
" #seconds #to #"+Integer.toString(heraldNews.get(i).getLimit())+
" #seconds: \""+heraldNews.get(i).getNews()+"\"");
} catch (IndexOutOfBoundsException ioobe) {
logger.error("ReadNewsAction: size of heraldNews = "+
Integer.toString(newssize), ioobe);
}
if(i!=(newssize-1)){
sb.append("; ");
}
}
npc.say(sb.toString());
}
}
/**
* npc says his job list
*/
class ReadNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
int newssize = heraldNews.size();
if(newssize==0){
npc.say("Moja lista ogłoszeń jest pusta.");
return;
}
StringBuilder sb=new StringBuilder();
sb.append("Oto " + Grammar.isare(newssize) + " moich aktualnych ogłoszeń: ");
for(int i=0; i<newssize;i++){
// will add 1 to position numbers to show position 0 as 1.
logger.info("info: index "+Integer.toString(i));
try {
sb.append("\""+heraldNews.get(i).getNews()+"\"");
} catch (IndexOutOfBoundsException ioobe) {
logger.error("ReadNewsAction: size of heraldNews = "+
Integer.toString(newssize), ioobe);
}
if(i!=(newssize-1)){
sb.append("; ");
}
}
npc.say(sb.toString());
}
}
/**
* NPC adds new job to his job list.
*/
class WriteNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
String text = sentence.getOriginalText();
logger.info("Oryginalne zdanie: " + text);
final String[] starr = text.split(" ");
if(starr.length < 2){
npc.say("Zapomniałeś o czasie zakończenia. Jestem śmiertelnikiem i trochę stary. Wiesz o co chodzi.");
return;
}
try {
final int interval = Integer.parseInt(starr[1].trim());
final int limit = Integer.parseInt(starr[2].trim());
if(limit < interval){
npc.say("Nie mogę policzyć do "+Integer.toString(interval)+
" i "+Integer.toString(limit)+" jest mniejsza od " + Integer.toString(interval)+
". Powtórz proszę.");
return;
}
try {
text = text.substring(starr[0].length()).trim().
substring(starr[1].length()).trim().
substring(starr[2].length()).trim();
final String out="Interval: "+Integer.toString(interval)+", limit: "+
Integer.toString(limit)+", text: \""+text+"\"";
npc.say("Dobrze zapisałem sobie. "+out);
logger.info("Admin "+player.getName()+
" added announcement: " +out);
final HeraldListener tnl = new HeraldListener(heraldNews.size());
heraldNews.add(new HeraldNews(text, interval, limit, 0, tnl, heraldNews.size()));
turnNotifier.notifyInSeconds(interval,tnl);
} catch (IndexOutOfBoundsException ioobe) {
npc.say(FeelBad);
logger.error("WriteNewsAction: Error while parsing sentence "+sentence.toString(), ioobe);
}
} catch (NumberFormatException nfe) {
npc.say(DontUnderstand);
logger.info("Error while parsing numbers. Interval and limit is: "+"("+starr[0]+"), ("+starr[1]+")");
}
}
}
/**
* NPC removes one job from his job list.
*/
class RemoveNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
String text = sentence.getOriginalText();
final String[] starr = text.split(" ");
if(starr.length < 2){
npc.say("Powiedz mi numer ogłoszenia do usunięcia.");
return;
}
final String number = starr[1];
try {
final int i = Integer.parseInt(number)-1;
if (i < 0){
npc.say(BadJoke);
return;
}
if (heraldNews.size()==0) {
npc.say("Nie mam teraz ogłoszeń.");
return;
}
if(i>=(heraldNews.size())){
npc.say("Mam tylko "+ Integer.toString(heraldNews.size())+
" ogłoszeń w tym momencie.");
return;
}
logger.warn("Admin "+player.getName()+" removing announcement #"+
Integer.toString(i)+": interval "+
Integer.toString(heraldNews.get(i).getInterval())+", limit "+
Integer.toString(heraldNews.get(i).getLimit())+", text \""+
heraldNews.get(i).getNews()+"\"");
turnNotifier.dontNotify(heraldNews.get(i).getTNL());
heraldNews.remove(i);
npc.say("Dobrze już zapomniałem.");
} catch (NumberFormatException nfe) {
logger.error("RemoveNewsAction: cant remove "+number+" speech.", nfe);
npc.say(DontUnderstand);
}
}
}
/**
* npc removes all jobs from his job list
*/
class ClearNewsAction implements ChatAction {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc){
logger.info("ClearAllAction: Admin "+player.getName()+
" cleared announcement list.");
for (int i=0; i<heraldNews.size(); i++) {
turnNotifier.dontNotify(heraldNews.get(i).getTNL());
}
if(heraldNews.size()!=0){
npc.say("Ufff mam trochę czasu na odpoczynek. Słyszałem, że jest jakaś gra w mieście Semos?");
heraldNews.clear();
} else {
npc.say("Oh dziękuję za troskę, ale wszystko w porządku.");
}
}
}
/**
* Finite states machine logic for herald.
*/
@Override
public void createDialog() {
add(ConversationStates.IDLE,
Arrays.asList("hi", "hola", "hello", "heya", "cześć"),
new NotCondition(new AdminCondition(REQUIRED_ADMINLEVEL_INFO)),
ConversationStates.IDLE,
null, new ReadNewsAction());
add(ConversationStates.IDLE,
Arrays.asList("hi", "hola", "hello", "heya", "cześć"),
new AdminCondition(REQUIRED_ADMINLEVEL_INFO),
ConversationStates.ATTENDING,
HiOldFriend, null);
add(ConversationStates.ATTENDING,
Arrays.asList("help", "pomoc"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
WillHelp, null);
add(ConversationStates.ATTENDING,
Arrays.asList("speech", "remove", "usuń"),
new NotCondition(new AdminCondition(REQUIRED_ADMINLEVEL_SET)),
ConversationStates.ATTENDING,
TooScared, null);
add(ConversationStates.ATTENDING,
Arrays.asList("help", "pomoc"),
new NotCondition(new AdminCondition(REQUIRED_ADMINLEVEL_SET)),
ConversationStates.ATTENDING,
InfoOnly, new ReadJobsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("info", "list", "tasks", "news", "informacje", "zadania", "nowości"),
new AdminCondition(REQUIRED_ADMINLEVEL_INFO),
ConversationStates.ATTENDING,
null, new ReadJobsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("speech", "powiedz"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
null, new WriteNewsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("remove", "usuń"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
null, new RemoveNewsAction());
add(ConversationStates.ATTENDING,
Arrays.asList("clear", "wyczyść"),
new AdminCondition(REQUIRED_ADMINLEVEL_SET),
ConversationStates.ATTENDING,
null, new ClearNewsAction());
addGoodbye();
}
};
zone.assignRPObjectID(npc);
npc.setEntityClass("heraldnpc");
npc.setPosition(x, y);
npc.initHP(100);
npc.setDirection(Direction.LEFT);
return(npc);
}
}
|
631_0 | package com.nianticproject.ingress.common.inventory.ui;
import com.nianticproject.ingress.common.model.PlayerModel;
import com.nianticproject.ingress.gameentity.GameEntity;
import com.nianticproject.ingress.gameentity.components.ItemRarity;
import com.nianticproject.ingress.shared.ItemType;
import java.util.Collection;
import java.util.List;
public class IndistinguishableItems {
public ItemType getType() {
return null;
}
public int getLevel() {
return 0;
}
public ItemRarity getRarity() {
return null;
}
public int getCount() {
return 0;
}
public GameEntity getEntity() {
return null;
}
// playerModel jest chyba wykorzystywany do sortowania kluczy po odległości do bieżącej lokalizacji. Może być nullem
public static List<IndistinguishableItems> fromItemsByPlayerInfo(PlayerModel playerModel, Collection items) {
return null;
}
}
| broo2s/ingress-apk-mod | ifc/com/nianticproject/ingress/common/inventory/ui/IndistinguishableItems.java | 295 | // playerModel jest chyba wykorzystywany do sortowania kluczy po odległości do bieżącej lokalizacji. Może być nullem | line_comment | pl | package com.nianticproject.ingress.common.inventory.ui;
import com.nianticproject.ingress.common.model.PlayerModel;
import com.nianticproject.ingress.gameentity.GameEntity;
import com.nianticproject.ingress.gameentity.components.ItemRarity;
import com.nianticproject.ingress.shared.ItemType;
import java.util.Collection;
import java.util.List;
public class IndistinguishableItems {
public ItemType getType() {
return null;
}
public int getLevel() {
return 0;
}
public ItemRarity getRarity() {
return null;
}
public int getCount() {
return 0;
}
public GameEntity getEntity() {
return null;
}
// playerModel jest <SUF>
public static List<IndistinguishableItems> fromItemsByPlayerInfo(PlayerModel playerModel, Collection items) {
return null;
}
}
|
633_0 | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
| keencelia/oo-java2 | lab4/Poczta.java | 1,003 | /**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/ | block_comment | pl | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie <SUF>*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
|
633_1 | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
| keencelia/oo-java2 | lab4/Poczta.java | 1,003 | // za dużo kontroli dla doreczyciela | line_comment | pl | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo <SUF>
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
|
633_2 | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
| keencelia/oo-java2 | lab4/Poczta.java | 1,003 | // public List <Przesylka> dajPrzesylki() { | line_comment | pl | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <SUF>
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
|
633_3 | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
| keencelia/oo-java2 | lab4/Poczta.java | 1,003 | // żeby nie duplikowac informacji | line_comment | pl | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie <SUF>
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
|
633_4 | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
* @return
*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
| keencelia/oo-java2 | lab4/Poczta.java | 1,003 | /**
*
* @param przesylki
* @return
*/ | block_comment | pl | package mini.java.poczta;
import java.util.ArrayList;
import java.util.List;
public class Poczta {
private static Poczta mainPoczta = new Poczta();
private List <Doreczyciel> doreczyciele = new ArrayList <Doreczyciel>();
private List<Przesylka> przesylki = new ArrayList<Przesylka>();
private Poczta() {}
public static Poczta getPoczta() {
return mainPoczta;
}
public void addDoreczyciel(Doreczyciel d) {
doreczyciele.add(d);
}
/**
* ktoś dostarcza poczcie przesylki
*
* @param przesylki
*/
public void pobierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
}
// za dużo kontroli dla doreczyciela
// public List <Przesylka> dajPrzesylki() {
// return przesylki;
// }
public int ileMa() {
return this.przesylki.size();
}
public List <Przesylka> dajPrzesylki(Doreczyciel d) {
int ile=d.getIleMa();
List<Przesylka> dlaDoreczyciela = new ArrayList<Przesylka>();
List<String> nd = new ArrayList<String>(); // żeby nie duplikowac informacji
for (int i = 0; i < przesylki.size() && ile < d.getMaxPrzesylki(); i++) {
Przesylka p = przesylki.get(i);
if (!d.akceptuje(p)) {
if (!nd.contains(this.getClass().getSimpleName())) {
System.out.println(d.getClass().getSimpleName().toString() +
": nie dostarcza " + p.getClass().getSimpleName().toString());
nd.add(this.getClass().getSimpleName());
}
} else {
przesylki.remove(p);
dlaDoreczyciela.add(p);
ile++;
}
}
return dlaDoreczyciela;
}
/**
*
* @param przesylki
<SUF>*/
public boolean odbierzPrzesylki(List <Przesylka> przesylki) {
this.przesylki.addAll(przesylki);
return true;
}
/**
*
*/
public void doreczPrzesylki() {
int pracuje = 0, niepracuje=0;
for (Doreczyciel d: this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) pracuje++;
else niepracuje++;
}
System.out.println("Pracuje " + pracuje + " doreczycieli");
if (niepracuje > 0) {
System.out.println("Nie pracuje " + niepracuje + " doreczycieli");
}
System.out.println("Jest " + przesylki.size() + " przesylek do dostarczenia");
while (przesylki.size() > 0) {
for (Doreczyciel d : this.doreczyciele) {
if (d.isWpracy() && !d.isZajety()) {
d.doreczPrzesylki();
}
}
System.out.println("Zostalo " + przesylki.size() + " przesylek do dostarczenia");
}
}
}
|
638_21 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - <SUF>
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_43 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // login* - login użytkownika w serwisie
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - <SUF>
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_44 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // pass* - hasło użytkownika w serwisie
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - <SUF>
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_45 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - <SUF>
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_46 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - <SUF>
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_48 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - <SUF>
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_49 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // userNotFound - użytkownik nie istnieje lub podano błędne hasło
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - <SUF>
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_50 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // emptyUrl - nie podano w parametrach adresu URL pliku
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - <SUF>
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_51 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - <SUF>
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_53 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - <SUF>
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_54 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // userAccountNotPremium - konto użytkownika nie posiada dostępu premium
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - <SUF>
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
638_55 | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/ShareHostEu.java | 6,360 | // userCanNotDownload - użytkownik nie może pobrać pliku z innych powodów (np. brak transferu)
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2014 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.html.Form;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "sharehost.eu" }, urls = { "https?://(www\\.)?sharehost\\.eu/[^<>\"]*?/(.*)" })
public class ShareHostEu extends PluginForHost {
public ShareHostEu(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://sharehost.eu/premium.html");
// this.setConfigElements();
}
@Override
public String getAGBLink() {
return "http://sharehost.eu/tos.html";
}
private int MAXCHUNKSFORFREE = 1;
private int MAXCHUNKSFORPREMIUM = 0;
private String MAINPAGE = "http://sharehost.eu";
private String PREMIUM_DAILY_TRAFFIC_MAX = "20 GB";
private String FREE_DAILY_TRAFFIC_MAX = "10 GB";
private static Object LOCK = new Object();
@Override
public AvailableStatus requestFileInformation(final DownloadLink downloadLink) throws IOException, PluginException {
// API CALL: /fapi/fileInfo
// Input:
// url* - link URL (required)
// filePassword - password for file (if exists)
br.postPage(MAINPAGE + "/fapi/fileInfo", "url=" + downloadLink.getDownloadURL());
// Output:
// fileName - file name
// filePath - file path
// fileSize - file size in bytes
// fileAvailable - true/false
// fileDescription - file description
// Errors:
// emptyUrl
// invalidUrl - wrong url format, too long or contauns invalid characters
// fileNotFound
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
final String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if ("fileNotFound".equals(error)) {
return AvailableStatus.FALSE;
} else if ("emptyUrl".equals(error)) {
return AvailableStatus.UNCHECKABLE;
} else {
return AvailableStatus.UNCHECKED;
}
}
String fileName = PluginJSonUtils.getJsonValue(br, "fileName");
// String filePath = PluginJSonUtils.getJsonValue(br, "filePath");
String fileSize = PluginJSonUtils.getJsonValue(br, "fileSize");
String fileAvailable = PluginJSonUtils.getJsonValue(br, "fileAvailable");
// String fileDescription = PluginJSonUtils.getJsonValue(br, "fileDescription");
if ("true".equals(fileAvailable)) {
if (fileName == null || fileSize == null) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
fileName = Encoding.htmlDecode(fileName.trim());
downloadLink.setFinalFileName(Encoding.htmlDecode(fileName.trim()));
downloadLink.setDownloadSize(SizeFormatter.getSize(fileSize));
downloadLink.setAvailable(true);
} else {
downloadLink.setAvailable(false);
}
if (!downloadLink.isAvailabilityStatusChecked()) {
return AvailableStatus.UNCHECKED;
}
if (downloadLink.isAvailabilityStatusChecked() && !downloadLink.isAvailable()) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
return AvailableStatus.TRUE;
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
AccountInfo ai = new AccountInfo();
String accountResponse;
try {
accountResponse = login(account, true);
} catch (PluginException e) {
if (e.getLinkStatus() == LinkStatus.ERROR_PREMIUM) {
account.setProperty("cookies", Property.NULL);
final String errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("Maintenance")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, e.getMessage(), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE, e).localizedMessage(e.getLocalizedMessage());
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Login failed: " + errorMessage, PluginException.VALUE_ID_PREMIUM_DISABLE, e);
}
} else {
throw e;
}
}
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
String userIsPremium = PluginJSonUtils.getJsonValue(accountResponse, "userIsPremium");
String userPremiumExpire = PluginJSonUtils.getJsonValue(accountResponse, "userPremiumExpire");
String userTrafficToday = PluginJSonUtils.getJsonValue(accountResponse, "userTrafficToday");
long userTrafficLeft = Long.parseLong(userTrafficToday);
ai.setTrafficLeft(userTrafficLeft);
if ("true".equals(userIsPremium)) {
ai.setProperty("premium", "true");
// ai.setTrafficMax(PREMIUM_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(PREMIUM_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("PREMIUM"));
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
try {
if (userPremiumExpire != null) {
Date date = dateFormat.parse(userPremiumExpire);
ai.setValidUntil(date.getTime());
}
} catch (final Exception e) {
logger.log(e);
}
} else {
ai.setProperty("premium", "false");
// ai.setTrafficMax(FREE_DAILY_TRAFFIC_MAX); // Compile error
ai.setTrafficMax(SizeFormatter.getSize(FREE_DAILY_TRAFFIC_MAX));
ai.setStatus(getPhrase("FREE"));
}
account.setValid(true);
return ai;
}
private String login(final Account account, final boolean force) throws Exception, PluginException {
synchronized (LOCK) {
try {
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
// API CALL: /fapi/userInfo
// Input:
// login*
// pass*
br.postPage(MAINPAGE + "/fapi/userInfo", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()));
// Output:
// userLogin - login
// userEmail - e-mail
// userIsPremium - true/false
// userPremiumExpire - premium expire date
// userTrafficToday - daily traffic left (bytes)
// Errors:
// emptyLoginOrPassword
// userNotFound
final String response = br.toString();
if ("false".equals(PluginJSonUtils.getJsonValue(br, "success"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("INVALID_LOGIN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ("true".equals(PluginJSonUtils.getJsonValue(br, "userIsPremium"))) {
account.setProperty("premium", "true");
} else {
account.setProperty("premium", "false");
}
br.setFollowRedirects(true);
br.postPage(MAINPAGE + "/index.php", "v=files%7Cmain&c=aut&f=login&friendlyredir=1&usr_login=" + Encoding.urlEncode(account.getUser()) + "&usr_pass=" + Encoding.urlEncode(account.getPass()));
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
/** Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("cookies", cookies);
return response;
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink);
}
public void doFree(final DownloadLink downloadLink) throws Exception, PluginException {
br.getPage(downloadLink.getDownloadURL());
setMainPage(downloadLink.getDownloadURL());
br.setCookiesExclusive(true);
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.setAcceptLanguage("pl-PL,pl;q=0.9,en;q=0.8");
br.setFollowRedirects(false);
String fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)'>Wolne pobieranie</a>").getMatch(0);
if (fileId == null) {
fileId = br.getRegex("<a href='/\\?v=download_free&fil=(\\d+)' class='btn btn_gray'>Wolne pobieranie</a>").getMatch(0);
}
br.getPage(MAINPAGE + "/?v=download_free&fil=" + fileId);
Form dlForm = br.getFormbyAction("http://sharehost.eu/");
String dllink = "";
for (int i = 0; i < 3; i++) {
String waitTime = br.getRegex("var iFil=" + fileId + ";[\r\t\n ]+const DOWNLOAD_WAIT=(\\d+)").getMatch(0);
sleep(Long.parseLong(waitTime) * 1000l, downloadLink);
String captchaId = br.getRegex("<img src='/\\?c=aut&f=imageCaptcha&id=(\\d+)' id='captcha_img'").getMatch(0);
String code = getCaptchaCode(MAINPAGE + "/?c=aut&f=imageCaptcha&id=" + captchaId, downloadLink);
dlForm.put("cap_key", code);
// br.submitForm(dlForm);
br.postPage(MAINPAGE + "/", "v=download_free&c=dwn&f=getWaitedLink&cap_id=" + captchaId + "&fil=" + fileId + "&cap_key=" + code);
if (br.containsHTML("Nie możesz w tej chwili pobrać kolejnego pliku")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("DOWNLOAD_LIMIT"), 5 * 60 * 1000l);
} else if (br.containsHTML("Wpisano nieprawidłowy kod z obrazka")) {
logger.info("wrong captcha");
} else {
dllink = br.getRedirectLocation();
break;
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Can't find final download link/Captcha errors!", -1l);
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, MAXCHUNKSFORFREE);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("<ul><li>Brak wolnych slotów do pobrania tego pliku. Zarejestruj się, aby pobrać plik.</li></ul>")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, getPhrase("NO_FREE_SLOTS"), 5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
void setLoginData(final Account account) throws Exception {
br.getPage(MAINPAGE);
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(MAINPAGE, key, value);
}
}
}
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
String downloadUrl = downloadLink.getPluginPatternMatcher();
setMainPage(downloadUrl);
br.setFollowRedirects(true);
String loginInfo = login(account, false);
boolean isPremium = "true".equals(account.getProperty("premium"));
// long userTrafficleft;
// try {
// userTrafficleft = Long.parseLong(getJson(loginInfo, "userTrafficToday"));
// } catch (Exception e) {
// userTrafficleft = 0;
// }
// if (isPremium || (!isPremium && userTrafficleft > 0)) {
requestFileInformation(downloadLink);
if (isPremium) {
// API CALLS: /fapi/fileDownloadLink
// INput:
// login* - login użytkownika w serwisie
// pass* - hasło użytkownika w serwisie
// url* - adres URL pliku w dowolnym z formatów generowanych przez serwis
// filePassword - hasło dostępu do pliku (o ile właściciel je ustanowił)
// Output:
// fileUrlDownload (link valid for 24 hours)
br.postPage(MAINPAGE + "/fapi/fileDownloadLink", "login=" + Encoding.urlEncode(account.getUser()) + "&pass=" + Encoding.urlEncode(account.getPass()) + "&url=" + downloadLink.getDownloadURL());
// Errors
// emptyLoginOrPassword - nie podano w parametrach loginu lub hasła
// userNotFound - użytkownik nie istnieje lub podano błędne hasło
// emptyUrl - nie podano w parametrach adresu URL pliku
// invalidUrl - podany adres URL jest w nieprawidłowym formacie, zawiera nieprawidłowe znaki lub jest zbyt długi
// fileNotFound - nie znaleziono pliku dla podanego adresu URL
// filePasswordNotMatch - podane hasło dostępu do pliku jest niepoprawne
// userAccountNotPremium - konto użytkownika nie posiada dostępu premium
// userCanNotDownload - <SUF>
String success = PluginJSonUtils.getJsonValue(br, "success");
if ("false".equals(success)) {
if ("userCanNotDownload".equals(PluginJSonUtils.getJsonValue(br, "error"))) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "No traffic left!");
} else if (("fileNotFound".equals(PluginJSonUtils.getJsonValue(br, "error")))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
String finalDownloadLink = PluginJSonUtils.getJsonValue(br, "fileUrlDownload");
setLoginData(account);
String dllink = finalDownloadLink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, MAXCHUNKSFORPREMIUM);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!" + "Response: " + dl.getConnection().getResponseMessage() + ", code: " + dl.getConnection().getResponseCode() + "\n" + dl.getConnection().getContentType());
br.followConnection();
logger.warning("br returns:" + br.toString());
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
} else {
MAXCHUNKSFORPREMIUM = 1;
setLoginData(account);
handleFree(downloadLink);
}
}
private static AtomicBoolean yt_loaded = new AtomicBoolean(false);
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
void setMainPage(String downloadUrl) {
if (downloadUrl.contains("https://")) {
MAINPAGE = "https://sharehost.eu";
} else {
MAINPAGE = "http://sharehost.eu";
}
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("nopremium"))) {
/* free accounts also have captchas */
return true;
}
if (acc.getStringProperty("session_type") != null && !"premium".equalsIgnoreCase(acc.getStringProperty("session_type"))) {
return true;
}
return false;
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("PREMIUM", "Premium User");
put("FREE", "Free (Registered) User");
put("LOGIN_FAILED_NOT_PREMIUM", "Login failed or not Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Login Error");
put("LOGIN_FAILED", "Login failed!\r\nPlease check your Username and Password!");
put("NO_TRAFFIC", "No traffic left");
put("DOWNLOAD_LIMIT", "You can only download 1 file per 15 minutes");
put("CAPTCHA_ERROR", "Wrong Captcha code in 3 trials!");
put("NO_FREE_SLOTS", "No free slots for downloading this file");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("INVALID_LOGIN", "\r\nNieprawidłowy login/hasło!\r\nCzy jesteś pewien, że poprawnie wprowadziłeś nazwę użytkownika i hasło? Sugestie:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź nazwę użytkownika/hasło ręcznie, bez użycia funkcji Kopiuj i Wklej.");
put("PREMIUM", "Użytkownik Premium");
put("FREE", "Użytkownik zarejestrowany (darmowy)");
put("LOGIN_FAILED_NOT_PREMIUM", "Nieprawidłowe konto lub konto nie-Premium");
put("LOGIN_ERROR", "ShareHost.Eu: Błąd logowania");
put("LOGIN_FAILED", "Logowanie nieudane!\r\nZweryfikuj proszę Nazwę Użytkownika i Hasło!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("DOWNLOAD_LIMIT", "Można pobrać maksymalnie 1 plik na 15 minut");
put("CAPTCHA_ERROR", "Wprowadzono 3-krotnie nieprawiłowy kod Captcha!");
put("NO_FREE_SLOTS", "Brak wolnych slotów do pobrania tego pliku");
}
};
/**
* Returns a German/English translation of a phrase. We don't use the JDownloader translation framework since we need only German and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
if ("pl".equals(System.getProperty("user.language")) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} |
642_14 | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.util.Locale;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.Account.AccountType;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.captcha.v2.challenge.recaptcha.v2.CaptchaHelperHostPluginRecaptchaV2;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "freedisc.pl" }, urls = { "https?://(www\\.)?freedisc\\.pl/(#(!|%21))?[A-Za-z0-9\\-_]+,f-\\d+" })
public class FreeDiscPl extends PluginForHost {
public FreeDiscPl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://freedisc.pl/");
this.setStartIntervall(1000);
try {
Browser.setRequestIntervalLimitGlobal("freedisc.pl", 250, 20, 60000);
} catch (final Throwable e) {
}
}
@Override
public String getAGBLink() {
return "http://freedisc.pl/regulations";
}
public void correctDownloadLink(DownloadLink link) {
link.setUrlDownload(link.getDownloadURL().replace("/#!", "/"));
}
/* Connection stuff */
private static final boolean FREE_RESUME = false;
private static final int FREE_MAXCHUNKS = 1;
private static final int FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_FREE_RESUME = true;
private static final int ACCOUNT_FREE_MAXCHUNKS = 0;
private static final int ACCOUNT_FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_PREMIUM_RESUME = true;
private static final int ACCOUNT_PREMIUM_MAXCHUNKS = 0;
private static final int ACCOUNT_PREMIUM_MAXDOWNLOADS = 20;
private static final String KNOWN_EXTENSIONS = "asf|avi|flv|m4u|m4v|mov|mkv|mp4|mpeg4?|mpg|ogm|vob|wmv|webm";
protected static Cookies botSafeCookies = new Cookies();
private Browser prepBR(final Browser br) {
prepBRStatic(br);
synchronized (botSafeCookies) {
if (!botSafeCookies.isEmpty()) {
br.setCookies(this.getHost(), botSafeCookies);
}
}
return br;
}
public static Browser prepBRStatic(final Browser br) {
br.setAllowedResponseCodes(410);
return br;
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws Exception {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setReadTimeout(3 * 60 * 1000);
br.setConnectTimeout(3 * 60 * 1000);
prepBR(this.br);
br.getPage(link.getDownloadURL());
if (isBotBlocked(this.br)) {
return AvailableStatus.UNCHECKABLE;
} else if (br.getRequest().getHttpConnection().getResponseCode() == 410) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
} else if (this.br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("Ten plik został usunięty przez użytkownika lub administratora|Użytkownik nie posiada takiego pliku|<title>404 error") || !br.getURL().contains(",f")) {
/* Check this last as botBlocked also contains 404. */
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
// Handle no public files as offline
if (br.containsHTML("Ten plik nie jest publicznie dostępny")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
String filename = br.getRegex("itemprop=\"name\">([^<>\"]*?)</h2>").getMatch(0);
// itemprop="name" style=" font-size: 17px; margin-top: 6px;">Alternatywne Metody Analizy technicznej .pdf</h1>
if (filename == null) {
filename = br.getRegex("itemprop=\"name\"( style=\"[^<>\"/]+\")?>([^<>\"]*?)</h1>").getMatch(1);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
final String fpat = "\\s*([0-9]+(?:[\\.,][0-9]+)?\\s*[A-Z]{1,2})";
String filesize = br.getRegex("class='frameFilesSize'>Rozmiar pliku</div>[\t\n\r ]+<div class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("Rozmiar pliku</div>[\t\n\r ]+<div class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("</i> Rozmiar pliku</div><div class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("<i class=\"icon-hdd\"></i>\\s*Rozmiar\\s*</div>\\s*<div class='value'>" + fpat).getMatch(0);
}
}
}
}
final String storedfileName = link.getName();
String storedExt = "";
if (storedfileName != null) {
storedExt = storedfileName.substring(storedfileName.lastIndexOf(".") + 1);
}
if (link.getName() == null || (storedExt != null && !storedExt.matches(KNOWN_EXTENSIONS))) {
link.setName(Encoding.htmlDecode(filename.trim()));
}
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink, FREE_RESUME, FREE_MAXCHUNKS, "free_directlink");
}
private void doFree(final DownloadLink downloadLink, boolean resumable, int maxchunks, final String directlinkproperty) throws Exception, PluginException {
if (isBotBlocked(this.br)) {
this.handleAntiBot(this.br);
/* Important! Check status if we were blocked before! */
requestFileInformation(downloadLink);
}
String dllink = checkDirectLink(downloadLink, directlinkproperty);
final boolean isvideo = downloadLink.getBooleanProperty("isvideo", false);
if (dllink != null) {
/* Check if directlinks comes from a stream */
if (isvideo) {
/* Stream-downloads always have no limits! */
resumable = true;
maxchunks = 0;
}
} else {
final boolean videostreamIsAvailable = br.containsHTML("rel=\"video_src\"");
final String videoEmbedUrl = br.getRegex("<iframe src=\"(https?://freedisc\\.pl/embed/video/\\d+[^<>\"]*?)\"").getMatch(0);
resumable = true;
maxchunks = 0;
final String fid = new Regex(downloadLink.getDownloadURL(), "(\\d+)$").getMatch(0);
postPageRaw("//freedisc.pl/download/payment_info", "{\"item_id\":\"" + fid + "\",\"item_type\":1,\"code\":\"\",\"file_id\":" + fid + ",\"no_headers\":1,\"menu_visible\":0}");
br.getRequest().setHtmlCode(Encoding.unicodeDecode(this.br.toString()));
if (br.containsHTML("Pobranie plików większych jak [0-9\\.]+ (MB|GB|TB), wymaga opłacenia kosztów transferu")) {
logger.info("File is premiumonly --> Maybe stream download is possible!");
/* Premiumonly --> But maybe we can download the video-stream */
if (videostreamIsAvailable && videoEmbedUrl != null) {
logger.info("Seems like a stream is available --> Trying to find downloadlink");
/* Stream-downloads always have no limits! */
resumable = true;
maxchunks = 0;
getPage(videoEmbedUrl);
dllink = br.getRegex("data-video-url=\"(https?://[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
dllink = br.getRegex("player\\.swf\\?file=(https?://[^<>\"]*?)\"").getMatch(0);
}
if (dllink != null) {
logger.info("Stream download handling seems to have worked successfully");
String ext = null;
final String currentFname = downloadLink.getName();
if (currentFname.contains(".")) {
ext = currentFname.substring(currentFname.lastIndexOf("."));
}
if (ext == null || (ext != null && ext.length() <= 5)) {
downloadLink.setFinalFileName(downloadLink.getName() + ".mp4");
} else if (ext.length() > 5) {
ext = dllink.substring(dllink.lastIndexOf(".") + 1);
if (ext.matches(KNOWN_EXTENSIONS)) {
downloadLink.setFinalFileName(downloadLink.getName() + "." + ext);
}
}
downloadLink.setProperty("isvideo", true);
} else {
logger.info("Stream download handling seems to have failed");
}
}
if (dllink == null) {
/* We failed to find a stream downloadlink so the file must be premium/free-account only! */
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
}
} else {
String downloadUrlJson = PluginJSonUtils.getJsonNested(br, "download_data");
dllink = PluginJSonUtils.getJsonValue(downloadUrlJson, "download_url") + PluginJSonUtils.getJsonValue(downloadUrlJson, "item_id") + "/" + PluginJSonUtils.getJsonValue(downloadUrlJson, "time");
// dllink = "http://freedisc.pl/download/" + new Regex(downloadLink.getDownloadURL(), "(\\d+)$").getMatch(0);
downloadLink.setProperty("isvideo", false);
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, downloadLink, dllink, resumable, maxchunks);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (this.br.containsHTML("Ten plik jest chwilowo niedos")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error", 5 * 60 * 1000l);
}
if (br.getURL().contains("freedisc.pl/pierrw,f-")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error", 5 * 60 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
String server_filename = getFileNameFromDispositionHeader(dl.getConnection());
if (server_filename != null) {
server_filename = Encoding.htmlDecode(server_filename);
downloadLink.setFinalFileName(server_filename);
} else {
final String urlName = getFileNameFromURL(dl.getConnection().getURL());
if (downloadLink.getFinalFileName() == null && urlName != null && org.appwork.utils.Files.getExtension(urlName) != null) {
downloadLink.setFinalFileName(downloadLink.getName() + org.appwork.utils.Files.getExtension(urlName));
}
}
downloadLink.setProperty(directlinkproperty, dllink);
dl.startDownload();
}
public static boolean isBotBlocked(final Browser br) {
return br.containsHTML("Przez roboty internetowe nasze serwery się gotują|g-recaptcha");
}
private void getPage(final String url) throws Exception {
br.getPage(url);
handleAntiBot(this.br);
}
private void postPageRaw(final String url, final String parameters) throws Exception {
this.br.postPageRaw(url, parameters);
handleAntiBot(this.br);
}
private void handleAntiBot(final Browser br) throws Exception {
if (isBotBlocked(this.br)) {
/* Process anti-bot captcha */
logger.info("Login captcha / spam protection detected");
final DownloadLink originalDownloadLink = this.getDownloadLink();
final DownloadLink downloadlinkToUse;
try {
if (originalDownloadLink != null) {
downloadlinkToUse = originalDownloadLink;
} else {
/* E.g. for login process */
downloadlinkToUse = new DownloadLink(this, "Account Login " + this.getHost(), this.getHost(), MAINPAGE, true);
}
this.setDownloadLink(downloadlinkToUse);
final String recaptchaV2Response = new CaptchaHelperHostPluginRecaptchaV2(this, br).getToken();
br.postPage(br.getURL(), "g-recaptcha-response=" + Encoding.urlEncode(recaptchaV2Response));
if (isBotBlocked(this.br)) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Anti-Bot block", 5 * 60 * 1000l);
}
} finally {
if (originalDownloadLink != null) {
this.setDownloadLink(originalDownloadLink);
}
}
// save the session!
synchronized (botSafeCookies) {
botSafeCookies = br.getCookies(this.getHost());
}
}
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
br2.setFollowRedirects(true);
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return FREE_MAXDOWNLOADS;
}
private static final String MAINPAGE = "http://freedisc.pl";
private static Object LOCK = new Object();
private void login(final Account account, final boolean force) throws Exception {
synchronized (LOCK) {
try {
// Load cookies
br.setCookiesExclusive(true);
prepBR(br);
br.setFollowRedirects(false);
final Cookies cookies = account.loadCookies("");
if (cookies != null) {
/* Always try to re-use cookies. */
br.setCookies(this.getHost(), cookies);
br.getPage("https://" + this.getHost() + "/");
if (br.containsHTML("id=\"btnLogout\"")) {
return;
}
}
Browser br = prepBR(new Browser());
br.getPage("https://" + this.getHost() + "/");
// this is done via ajax!
br.getHeaders().put("Accept", "application/json, text/javascript, */*; q=0.01");
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.getHeaders().put("Content-Type", "application/json");
br.getHeaders().put("Cache-Control", null);
br.postPageRaw("/account/signin_set", "{\"email_login\":\"" + account.getUser() + "\",\"password_login\":\"" + account.getPass() + "\",\"remember_login\":1,\"provider_login\":\"\"}");
if (br.getCookie(MAINPAGE, "login_remember") == null && br.getCookie(MAINPAGE, "cookie_login_remember") == null) {
final String lang = System.getProperty("user.language");
if ("de".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername oder ungültiges Passwort!\r\nSchnellhilfe: \r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen?\r\nFalls dein Passwort Sonderzeichen enthält, ändere es und versuche es erneut!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędna nazwa użytkownika/hasło lub nie obsługiwany typ konta!\r\nSzybka pomoc:\r\nJesteś pewien, że poprawnie wprowadziłeś użytkownika/hasło?\r\nJeśli twoje hasło zawiera niektóre specjalne znaki - proszę zmień je (usuń) i wprowadź dane ponownie!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password!\r\nQuick help:\r\nYou're sure that the username and password you entered are correct?\r\nIf your password contains special characters, change it (remove them) and try again!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
handleAntiBot(this.br);
/* Only free accounts are supported */
account.setType(AccountType.FREE);
account.saveCookies(br.getCookies(this.getHost()), "");
// reload into standard browser
this.br.setCookies(this.getHost(), account.loadCookies(""));
} catch (final PluginException e) {
account.clearCookies("");
throw e;
}
}
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
try {
login(account, true);
} catch (PluginException e) {
account.setValid(false);
throw e;
}
ai.setUnlimitedTraffic();
if (account.getType() == AccountType.FREE) {
/* free accounts can still have captcha */
account.setMaxSimultanDownloads(ACCOUNT_FREE_MAXDOWNLOADS);
account.setConcurrentUsePossible(false);
ai.setStatus("Free Account");
} else {
final String expire = br.getRegex("").getMatch(0);
if (expire == null) {
final String lang = System.getProperty("user.language");
if ("de".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername/Passwort oder nicht unterstützter Account Typ!\r\nSchnellhilfe: \r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen?\r\nFalls dein Passwort Sonderzeichen enthält, ändere es und versuche es erneut!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędna nazwa użytkownika/hasło lub nie obsługiwany typ konta!\r\nSzybka pomoc:\r\nJesteś pewien, że poprawnie wprowadziłeś użytkownika/hasło?\r\nJeśli twoje hasło zawiera niektóre specjalne znaki - proszę zmień je (usuń) i wprowadź dane ponownie!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or unsupported account type!\r\nQuick help:\r\nYou're sure that the username and password you entered are correct?\r\nIf your password contains special characters, change it (remove them) and try again!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
} else {
ai.setValidUntil(TimeFormatter.getMilliSeconds(expire, "dd MMMM yyyy", Locale.ENGLISH));
}
account.setMaxSimultanDownloads(ACCOUNT_PREMIUM_MAXDOWNLOADS);
account.setConcurrentUsePossible(true);
ai.setStatus("Premium Account");
}
account.setValid(true);
return ai;
}
@Override
public void handlePremium(final DownloadLink link, final Account account) throws Exception {
requestFileInformation(link);
login(account, false);
br.setFollowRedirects(false);
// br.getPage(link.getDownloadURL());
if (account.getType() == AccountType.FREE) {
doFree(link, ACCOUNT_FREE_RESUME, ACCOUNT_FREE_MAXCHUNKS, "account_free_directlink");
} else {
String dllink = this.checkDirectLink(link, "premium_directlink");
if (dllink == null) {
dllink = br.getRegex("").getMatch(0);
if (dllink == null) {
logger.warning("Final downloadlink (String is \"dllink\") regex didn't match!");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, link, dllink, ACCOUNT_PREMIUM_RESUME, ACCOUNT_PREMIUM_MAXCHUNKS);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
String server_filename = getFileNameFromHeader(dl.getConnection());
if (server_filename != null) {
server_filename = Encoding.htmlDecode(server_filename);
link.setFinalFileName(server_filename);
}
link.setProperty("premium_directlink", dllink);
dl.startDownload();
}
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/FreeDiscPl.java | 6,791 | // itemprop="name" style=" font-size: 17px; margin-top: 6px;">Alternatywne Metody Analizy technicznej .pdf</h1>
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.util.Locale;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.Account.AccountType;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import jd.plugins.components.PluginJSonUtils;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.captcha.v2.challenge.recaptcha.v2.CaptchaHelperHostPluginRecaptchaV2;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "freedisc.pl" }, urls = { "https?://(www\\.)?freedisc\\.pl/(#(!|%21))?[A-Za-z0-9\\-_]+,f-\\d+" })
public class FreeDiscPl extends PluginForHost {
public FreeDiscPl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://freedisc.pl/");
this.setStartIntervall(1000);
try {
Browser.setRequestIntervalLimitGlobal("freedisc.pl", 250, 20, 60000);
} catch (final Throwable e) {
}
}
@Override
public String getAGBLink() {
return "http://freedisc.pl/regulations";
}
public void correctDownloadLink(DownloadLink link) {
link.setUrlDownload(link.getDownloadURL().replace("/#!", "/"));
}
/* Connection stuff */
private static final boolean FREE_RESUME = false;
private static final int FREE_MAXCHUNKS = 1;
private static final int FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_FREE_RESUME = true;
private static final int ACCOUNT_FREE_MAXCHUNKS = 0;
private static final int ACCOUNT_FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_PREMIUM_RESUME = true;
private static final int ACCOUNT_PREMIUM_MAXCHUNKS = 0;
private static final int ACCOUNT_PREMIUM_MAXDOWNLOADS = 20;
private static final String KNOWN_EXTENSIONS = "asf|avi|flv|m4u|m4v|mov|mkv|mp4|mpeg4?|mpg|ogm|vob|wmv|webm";
protected static Cookies botSafeCookies = new Cookies();
private Browser prepBR(final Browser br) {
prepBRStatic(br);
synchronized (botSafeCookies) {
if (!botSafeCookies.isEmpty()) {
br.setCookies(this.getHost(), botSafeCookies);
}
}
return br;
}
public static Browser prepBRStatic(final Browser br) {
br.setAllowedResponseCodes(410);
return br;
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws Exception {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setReadTimeout(3 * 60 * 1000);
br.setConnectTimeout(3 * 60 * 1000);
prepBR(this.br);
br.getPage(link.getDownloadURL());
if (isBotBlocked(this.br)) {
return AvailableStatus.UNCHECKABLE;
} else if (br.getRequest().getHttpConnection().getResponseCode() == 410) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
} else if (this.br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("Ten plik został usunięty przez użytkownika lub administratora|Użytkownik nie posiada takiego pliku|<title>404 error") || !br.getURL().contains(",f")) {
/* Check this last as botBlocked also contains 404. */
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
// Handle no public files as offline
if (br.containsHTML("Ten plik nie jest publicznie dostępny")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
String filename = br.getRegex("itemprop=\"name\">([^<>\"]*?)</h2>").getMatch(0);
// itemprop="name" style=" <SUF>
if (filename == null) {
filename = br.getRegex("itemprop=\"name\"( style=\"[^<>\"/]+\")?>([^<>\"]*?)</h1>").getMatch(1);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
final String fpat = "\\s*([0-9]+(?:[\\.,][0-9]+)?\\s*[A-Z]{1,2})";
String filesize = br.getRegex("class='frameFilesSize'>Rozmiar pliku</div>[\t\n\r ]+<div class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("Rozmiar pliku</div>[\t\n\r ]+<div class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("</i> Rozmiar pliku</div><div class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("class='frameFilesCountNumber'>" + fpat).getMatch(0);
if (filesize == null) {
filesize = br.getRegex("<i class=\"icon-hdd\"></i>\\s*Rozmiar\\s*</div>\\s*<div class='value'>" + fpat).getMatch(0);
}
}
}
}
final String storedfileName = link.getName();
String storedExt = "";
if (storedfileName != null) {
storedExt = storedfileName.substring(storedfileName.lastIndexOf(".") + 1);
}
if (link.getName() == null || (storedExt != null && !storedExt.matches(KNOWN_EXTENSIONS))) {
link.setName(Encoding.htmlDecode(filename.trim()));
}
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
doFree(downloadLink, FREE_RESUME, FREE_MAXCHUNKS, "free_directlink");
}
private void doFree(final DownloadLink downloadLink, boolean resumable, int maxchunks, final String directlinkproperty) throws Exception, PluginException {
if (isBotBlocked(this.br)) {
this.handleAntiBot(this.br);
/* Important! Check status if we were blocked before! */
requestFileInformation(downloadLink);
}
String dllink = checkDirectLink(downloadLink, directlinkproperty);
final boolean isvideo = downloadLink.getBooleanProperty("isvideo", false);
if (dllink != null) {
/* Check if directlinks comes from a stream */
if (isvideo) {
/* Stream-downloads always have no limits! */
resumable = true;
maxchunks = 0;
}
} else {
final boolean videostreamIsAvailable = br.containsHTML("rel=\"video_src\"");
final String videoEmbedUrl = br.getRegex("<iframe src=\"(https?://freedisc\\.pl/embed/video/\\d+[^<>\"]*?)\"").getMatch(0);
resumable = true;
maxchunks = 0;
final String fid = new Regex(downloadLink.getDownloadURL(), "(\\d+)$").getMatch(0);
postPageRaw("//freedisc.pl/download/payment_info", "{\"item_id\":\"" + fid + "\",\"item_type\":1,\"code\":\"\",\"file_id\":" + fid + ",\"no_headers\":1,\"menu_visible\":0}");
br.getRequest().setHtmlCode(Encoding.unicodeDecode(this.br.toString()));
if (br.containsHTML("Pobranie plików większych jak [0-9\\.]+ (MB|GB|TB), wymaga opłacenia kosztów transferu")) {
logger.info("File is premiumonly --> Maybe stream download is possible!");
/* Premiumonly --> But maybe we can download the video-stream */
if (videostreamIsAvailable && videoEmbedUrl != null) {
logger.info("Seems like a stream is available --> Trying to find downloadlink");
/* Stream-downloads always have no limits! */
resumable = true;
maxchunks = 0;
getPage(videoEmbedUrl);
dllink = br.getRegex("data-video-url=\"(https?://[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
dllink = br.getRegex("player\\.swf\\?file=(https?://[^<>\"]*?)\"").getMatch(0);
}
if (dllink != null) {
logger.info("Stream download handling seems to have worked successfully");
String ext = null;
final String currentFname = downloadLink.getName();
if (currentFname.contains(".")) {
ext = currentFname.substring(currentFname.lastIndexOf("."));
}
if (ext == null || (ext != null && ext.length() <= 5)) {
downloadLink.setFinalFileName(downloadLink.getName() + ".mp4");
} else if (ext.length() > 5) {
ext = dllink.substring(dllink.lastIndexOf(".") + 1);
if (ext.matches(KNOWN_EXTENSIONS)) {
downloadLink.setFinalFileName(downloadLink.getName() + "." + ext);
}
}
downloadLink.setProperty("isvideo", true);
} else {
logger.info("Stream download handling seems to have failed");
}
}
if (dllink == null) {
/* We failed to find a stream downloadlink so the file must be premium/free-account only! */
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
}
} else {
String downloadUrlJson = PluginJSonUtils.getJsonNested(br, "download_data");
dllink = PluginJSonUtils.getJsonValue(downloadUrlJson, "download_url") + PluginJSonUtils.getJsonValue(downloadUrlJson, "item_id") + "/" + PluginJSonUtils.getJsonValue(downloadUrlJson, "time");
// dllink = "http://freedisc.pl/download/" + new Regex(downloadLink.getDownloadURL(), "(\\d+)$").getMatch(0);
downloadLink.setProperty("isvideo", false);
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, downloadLink, dllink, resumable, maxchunks);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (this.br.containsHTML("Ten plik jest chwilowo niedos")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error", 5 * 60 * 1000l);
}
if (br.getURL().contains("freedisc.pl/pierrw,f-")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error", 5 * 60 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
String server_filename = getFileNameFromDispositionHeader(dl.getConnection());
if (server_filename != null) {
server_filename = Encoding.htmlDecode(server_filename);
downloadLink.setFinalFileName(server_filename);
} else {
final String urlName = getFileNameFromURL(dl.getConnection().getURL());
if (downloadLink.getFinalFileName() == null && urlName != null && org.appwork.utils.Files.getExtension(urlName) != null) {
downloadLink.setFinalFileName(downloadLink.getName() + org.appwork.utils.Files.getExtension(urlName));
}
}
downloadLink.setProperty(directlinkproperty, dllink);
dl.startDownload();
}
public static boolean isBotBlocked(final Browser br) {
return br.containsHTML("Przez roboty internetowe nasze serwery się gotują|g-recaptcha");
}
private void getPage(final String url) throws Exception {
br.getPage(url);
handleAntiBot(this.br);
}
private void postPageRaw(final String url, final String parameters) throws Exception {
this.br.postPageRaw(url, parameters);
handleAntiBot(this.br);
}
private void handleAntiBot(final Browser br) throws Exception {
if (isBotBlocked(this.br)) {
/* Process anti-bot captcha */
logger.info("Login captcha / spam protection detected");
final DownloadLink originalDownloadLink = this.getDownloadLink();
final DownloadLink downloadlinkToUse;
try {
if (originalDownloadLink != null) {
downloadlinkToUse = originalDownloadLink;
} else {
/* E.g. for login process */
downloadlinkToUse = new DownloadLink(this, "Account Login " + this.getHost(), this.getHost(), MAINPAGE, true);
}
this.setDownloadLink(downloadlinkToUse);
final String recaptchaV2Response = new CaptchaHelperHostPluginRecaptchaV2(this, br).getToken();
br.postPage(br.getURL(), "g-recaptcha-response=" + Encoding.urlEncode(recaptchaV2Response));
if (isBotBlocked(this.br)) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Anti-Bot block", 5 * 60 * 1000l);
}
} finally {
if (originalDownloadLink != null) {
this.setDownloadLink(originalDownloadLink);
}
}
// save the session!
synchronized (botSafeCookies) {
botSafeCookies = br.getCookies(this.getHost());
}
}
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
br2.setFollowRedirects(true);
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return FREE_MAXDOWNLOADS;
}
private static final String MAINPAGE = "http://freedisc.pl";
private static Object LOCK = new Object();
private void login(final Account account, final boolean force) throws Exception {
synchronized (LOCK) {
try {
// Load cookies
br.setCookiesExclusive(true);
prepBR(br);
br.setFollowRedirects(false);
final Cookies cookies = account.loadCookies("");
if (cookies != null) {
/* Always try to re-use cookies. */
br.setCookies(this.getHost(), cookies);
br.getPage("https://" + this.getHost() + "/");
if (br.containsHTML("id=\"btnLogout\"")) {
return;
}
}
Browser br = prepBR(new Browser());
br.getPage("https://" + this.getHost() + "/");
// this is done via ajax!
br.getHeaders().put("Accept", "application/json, text/javascript, */*; q=0.01");
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.getHeaders().put("Content-Type", "application/json");
br.getHeaders().put("Cache-Control", null);
br.postPageRaw("/account/signin_set", "{\"email_login\":\"" + account.getUser() + "\",\"password_login\":\"" + account.getPass() + "\",\"remember_login\":1,\"provider_login\":\"\"}");
if (br.getCookie(MAINPAGE, "login_remember") == null && br.getCookie(MAINPAGE, "cookie_login_remember") == null) {
final String lang = System.getProperty("user.language");
if ("de".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername oder ungültiges Passwort!\r\nSchnellhilfe: \r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen?\r\nFalls dein Passwort Sonderzeichen enthält, ändere es und versuche es erneut!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędna nazwa użytkownika/hasło lub nie obsługiwany typ konta!\r\nSzybka pomoc:\r\nJesteś pewien, że poprawnie wprowadziłeś użytkownika/hasło?\r\nJeśli twoje hasło zawiera niektóre specjalne znaki - proszę zmień je (usuń) i wprowadź dane ponownie!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password!\r\nQuick help:\r\nYou're sure that the username and password you entered are correct?\r\nIf your password contains special characters, change it (remove them) and try again!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
handleAntiBot(this.br);
/* Only free accounts are supported */
account.setType(AccountType.FREE);
account.saveCookies(br.getCookies(this.getHost()), "");
// reload into standard browser
this.br.setCookies(this.getHost(), account.loadCookies(""));
} catch (final PluginException e) {
account.clearCookies("");
throw e;
}
}
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
try {
login(account, true);
} catch (PluginException e) {
account.setValid(false);
throw e;
}
ai.setUnlimitedTraffic();
if (account.getType() == AccountType.FREE) {
/* free accounts can still have captcha */
account.setMaxSimultanDownloads(ACCOUNT_FREE_MAXDOWNLOADS);
account.setConcurrentUsePossible(false);
ai.setStatus("Free Account");
} else {
final String expire = br.getRegex("").getMatch(0);
if (expire == null) {
final String lang = System.getProperty("user.language");
if ("de".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername/Passwort oder nicht unterstützter Account Typ!\r\nSchnellhilfe: \r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen?\r\nFalls dein Passwort Sonderzeichen enthält, ändere es und versuche es erneut!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(lang)) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędna nazwa użytkownika/hasło lub nie obsługiwany typ konta!\r\nSzybka pomoc:\r\nJesteś pewien, że poprawnie wprowadziłeś użytkownika/hasło?\r\nJeśli twoje hasło zawiera niektóre specjalne znaki - proszę zmień je (usuń) i wprowadź dane ponownie!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or unsupported account type!\r\nQuick help:\r\nYou're sure that the username and password you entered are correct?\r\nIf your password contains special characters, change it (remove them) and try again!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
} else {
ai.setValidUntil(TimeFormatter.getMilliSeconds(expire, "dd MMMM yyyy", Locale.ENGLISH));
}
account.setMaxSimultanDownloads(ACCOUNT_PREMIUM_MAXDOWNLOADS);
account.setConcurrentUsePossible(true);
ai.setStatus("Premium Account");
}
account.setValid(true);
return ai;
}
@Override
public void handlePremium(final DownloadLink link, final Account account) throws Exception {
requestFileInformation(link);
login(account, false);
br.setFollowRedirects(false);
// br.getPage(link.getDownloadURL());
if (account.getType() == AccountType.FREE) {
doFree(link, ACCOUNT_FREE_RESUME, ACCOUNT_FREE_MAXCHUNKS, "account_free_directlink");
} else {
String dllink = this.checkDirectLink(link, "premium_directlink");
if (dllink == null) {
dllink = br.getRegex("").getMatch(0);
if (dllink == null) {
logger.warning("Final downloadlink (String is \"dllink\") regex didn't match!");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, link, dllink, ACCOUNT_PREMIUM_RESUME, ACCOUNT_PREMIUM_MAXCHUNKS);
if (dl.getConnection().getContentType().contains("html")) {
logger.warning("The final dllink seems not to be a file!");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
String server_filename = getFileNameFromHeader(dl.getConnection());
if (server_filename != null) {
server_filename = Encoding.htmlDecode(server_filename);
link.setFinalFileName(server_filename);
}
link.setProperty("premium_directlink", dllink);
dl.startDownload();
}
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} |
645_12 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Browser.BrowserException;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "hellspy.cz" }, urls = { "https?://(www\\.|porn\\.)?hellspy\\.(cz|com|sk)/(soutez/|sutaz/)?[a-z0-9\\-]+/\\d+" })
public class HellSpyCz extends PluginForHost {
/*
* Sister sites: hellshare.cz, (and their other domains), hellspy.cz (and their other domains), using same dataservers but slightly
* different script
*/
/* Connection stuff */
private static final boolean FREE_RESUME = true;
private static final int FREE_MAXCHUNKS = -5;
private static final int FREE_MAXDOWNLOADS = 20;
// private static final boolean ACCOUNT_FREE_RESUME = true;
// private static final int ACCOUNT_FREE_MAXCHUNKS = 0;
// private static final int ACCOUNT_FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_PREMIUM_RESUME = true;
private static final int ACCOUNT_PREMIUM_MAXCHUNKS = -5;
private static final int ACCOUNT_PREMIUM_MAXDOWNLOADS = 20;
private static final String COOKIE_HOST = "http://hellspy.cz";
private static final boolean ALL_PREMIUMONLY = true;
private static final String HTML_IS_STREAM = "section\\-videodetail\"";
private static Object LOCK = new Object();
public HellSpyCz(final PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://www.en.hellshare.com/register");
/* Especially for premium - don't make too many requests in a short time or we'll get 503 responses. */
this.setStartIntervall(2000l);
}
@Override
public String getAGBLink() {
return "http://www.en.hellshare.com/terms";
}
@SuppressWarnings("deprecation")
@Override
public void correctDownloadLink(final DownloadLink link) throws Exception {
final String linkpart = new Regex(link.getDownloadURL(), "hellspy.(cz|com|sk)/(.+)").getMatch(1);
link.setUrlDownload("http://www.hellspy.cz/" + linkpart);
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
String filename = null;
String ext = null;
String filesize = null;
setBrowserExclusive();
br.setCustomCharset("utf-8");
br.getHeaders().put("Accept-Language", "en-gb;q=0.9, en;q=0.8");
br.setFollowRedirects(true);
this.br.setDebug(true);
try {
br.getPage(link.getDownloadURL());
} catch (final BrowserException e) {
if (br.getHttpConnection() != null && br.getHttpConnection().getResponseCode() == 502) {
link.getLinkStatus().setStatusText("We are sorry, but HellSpy is unavailable in your country");
return AvailableStatus.UNCHECKABLE;
}
}
if (br.containsHTML(">Soubor nenalezen<") || br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
filename = br.getRegex("<h1 title=\"([^<>\"]*?)\"").getMatch(0);
if (br.containsHTML(HTML_IS_STREAM)) {
/* Force extension */
ext = ".mp4";
} else {
/* Filesize is only given for non-streams */
filesize = br.getRegex("<span class=\"filesize right\">(\\d+(?:\\.\\d+)? <span>[^<>\"]*?)</span>").getMatch(0);
if (filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
filename = Encoding.htmlDecode(filename).trim();
if (ext != null) {
filename += ext;
}
link.setFinalFileName(filename);
if (filesize != null) {
filesize = filesize.replace("<span>", "");
link.setDownloadSize(SizeFormatter.getSize(filesize.replace(" ", "")));
}
return AvailableStatus.TRUE;
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return FREE_MAXDOWNLOADS;
}
@Override
public int getMaxSimultanPremiumDownloadNum() {
return ACCOUNT_PREMIUM_MAXDOWNLOADS;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
int maxchunks = FREE_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellShare is unavailable in your country", 4 * 60 * 60 * 1000l);
}
dllink = checkDirectLink(downloadLink, "free_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
/* No handling available for file links yet as all of them seem to be premium only! */
}
}
if (dllink == null && ALL_PREMIUMONLY) {
try {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
} catch (final Throwable e) {
if (e instanceof PluginException) {
throw (PluginException) e;
}
}
throw new PluginException(LinkStatus.ERROR_FATAL, "This file can only be downloaded by premium users");
}
br.setFollowRedirects(true);
br.setReadTimeout(120 * 1000);
/* Resume & unlimited chunks is definitly possible for stream links! */
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, FREE_RESUME, maxchunks);
if (!dl.getConnection().isContentDisposition()) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("Received html code insted of file");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("free_directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = openConnection(br2, dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@SuppressWarnings("deprecation")
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
int maxchunks = ACCOUNT_PREMIUM_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellSpy is unavailable in your country", 4 * 60 * 60 * 1000l);
}
login(account, false);
br.getPage(downloadLink.getDownloadURL());
dllink = checkDirectLink(downloadLink, "account_premium_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
final String filedownloadbutton = br.getURL() + "?download=1&iframe_view=popup+download_iframe_detail_popup";
URLConnectionAdapter con = openConnection(this.br, filedownloadbutton);
if (con.getContentType().contains("html")) {
br.followConnection();
dllink = br.getRegex("launchFullDownload\\(\\'(http[^<>\"]*?)\\'\\);\"").getMatch(0);
} else {
dllink = filedownloadbutton;
}
try {
con.disconnect();
} catch (final Throwable e) {
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dllink = dllink.replaceAll("\\\\", "");
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, ACCOUNT_PREMIUM_RESUME, maxchunks);
if (dl.getConnection().getResponseCode() == 503) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "Connection limit reached, please contact our support!", 5 * 60 * 1000l);
}
if (dl.getConnection().getContentType().contains("html")) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("The final dllink seems not to be a file!");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("account_premium_directlink", dllink);
dl.startDownload();
}
private String getStreamDirectlink() throws PluginException, IOException {
String play_url = br.getRegex("\"(/[^<>\"]*?do=play)\"").getMatch(0);
if (play_url == null) {
logger.warning("Stream-play-url is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
play_url = Encoding.htmlDecode(play_url);
this.br.getPage(play_url);
this.br.getRequest().setHtmlCode(br.toString().replace("\\", ""));
String dllink = br.getRegex("url: \"(http://stream\\d+\\.helldata\\.com[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
logger.warning("Stream-finallink is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
return dllink;
}
/** TODO: Maybe add support for time-accounts */
@SuppressWarnings("deprecation")
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
try {
login(account, true);
} catch (final PluginException e) {
ai.setStatus("Login failed");
account.setValid(false);
throw e;
}
br.getPage("/ucet/");
String traffic_left = br.getRegex("<td>Zakoupený:</td><td>(\\d+ MB)</td>").getMatch(0);
if (traffic_left == null) {
traffic_left = br.getRegex("<strong>Kreditů: </strong>([^<>\"]*?) \\– <a").getMatch(0);
}
if (traffic_left == null) {
ai.setStatus("Invalid/Unknown");
account.setValid(false);
return ai;
}
ai.setTrafficLeft(SizeFormatter.getSize(traffic_left));
ai.setValidUntil(-1);
ai.setStatus("Account with credits");
account.setProperty("free", false);
return ai;
}
@SuppressWarnings("unchecked")
public void login(final Account account, final boolean force) throws Exception {
synchronized (LOCK) {
try {
/* Load cookies */
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
boolean acmatch = Encoding.urlEncode(account.getUser()).equals(account.getStringProperty("name", Encoding.urlEncode(account.getUser())));
if (acmatch) {
acmatch = Encoding.urlEncode(account.getPass()).equals(account.getStringProperty("pass", Encoding.urlEncode(account.getPass())));
}
if (acmatch && ret != null && ret instanceof HashMap<?, ?> && !force) {
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(COOKIE_HOST, key, value);
}
return;
}
}
setBrowserExclusive();
br.setFollowRedirects(true);
br.setDebug(true);
br.getPage("http://www.hellspy.cz/?do=loginBox-loginpopup");
String login_action = br.getRegex("\"(http://(?:www\\.)?hell\\-share\\.com/user/login/\\?do=apiLoginForm-submit[^<>\"]*?)\"").getMatch(0);
if (login_action == null) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin defekt, bitte den JDownloader Support kontaktieren!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłąd wtyczki, skontaktuj się z Supportem JDownloadera!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin broken, please contact the JDownloader Support!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
login_action = Encoding.htmlDecode(login_action);
br.postPage(login_action, "username=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()) + "&permanent_login=on&submit_login=P%C5%99ihl%C3%A1sit+se&login=1&redir_url=http%3A%2F%2Fwww.hellspy.cz%2F%3Fdo%3DloginBox-login");
String permLogin = br.getCookie(br.getURL(), "permlogin");
if (permLogin == null || br.containsHTML("zadal jsi špatné uživatelské")) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername, Passwort oder login Captcha!\r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen? Versuche folgendes:\r\n1. Falls dein Passwort Sonderzeichen enthält, ändere es (entferne diese) und versuche es erneut!\r\n2. Gib deine Zugangsdaten per Hand (ohne kopieren/einfügen) ein.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędny użytkownik/hasło lub kod Captcha wymagany do zalogowania!\r\nUpewnij się, że prawidłowo wprowadziłes hasło i nazwę użytkownika. Dodatkowo:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź hasło i nazwę użytkownika ręcznie bez użycia opcji Kopiuj i Wklej.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or login captcha!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
/* Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(COOKIE_HOST);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
private URLConnectionAdapter openConnection(final Browser br, final String directlink) throws IOException {
URLConnectionAdapter con;
con = br.openGetConnection(directlink);
return con;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
return false;
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/HellSpyCz.java | 5,847 | //(www\\.|porn\\.)?hellspy\\.(cz|com|sk)/(soutez/|sutaz/)?[a-z0-9\\-]+/\\d+" }) | line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Browser.BrowserException;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "hellspy.cz" }, urls = { "https?://(www\\.|porn\\.)?hellspy\\.(cz|com|sk)/(soutez/|sutaz/)?[a-z0-9\\-]+/\\d+" }) <SUF>
public class HellSpyCz extends PluginForHost {
/*
* Sister sites: hellshare.cz, (and their other domains), hellspy.cz (and their other domains), using same dataservers but slightly
* different script
*/
/* Connection stuff */
private static final boolean FREE_RESUME = true;
private static final int FREE_MAXCHUNKS = -5;
private static final int FREE_MAXDOWNLOADS = 20;
// private static final boolean ACCOUNT_FREE_RESUME = true;
// private static final int ACCOUNT_FREE_MAXCHUNKS = 0;
// private static final int ACCOUNT_FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_PREMIUM_RESUME = true;
private static final int ACCOUNT_PREMIUM_MAXCHUNKS = -5;
private static final int ACCOUNT_PREMIUM_MAXDOWNLOADS = 20;
private static final String COOKIE_HOST = "http://hellspy.cz";
private static final boolean ALL_PREMIUMONLY = true;
private static final String HTML_IS_STREAM = "section\\-videodetail\"";
private static Object LOCK = new Object();
public HellSpyCz(final PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://www.en.hellshare.com/register");
/* Especially for premium - don't make too many requests in a short time or we'll get 503 responses. */
this.setStartIntervall(2000l);
}
@Override
public String getAGBLink() {
return "http://www.en.hellshare.com/terms";
}
@SuppressWarnings("deprecation")
@Override
public void correctDownloadLink(final DownloadLink link) throws Exception {
final String linkpart = new Regex(link.getDownloadURL(), "hellspy.(cz|com|sk)/(.+)").getMatch(1);
link.setUrlDownload("http://www.hellspy.cz/" + linkpart);
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
String filename = null;
String ext = null;
String filesize = null;
setBrowserExclusive();
br.setCustomCharset("utf-8");
br.getHeaders().put("Accept-Language", "en-gb;q=0.9, en;q=0.8");
br.setFollowRedirects(true);
this.br.setDebug(true);
try {
br.getPage(link.getDownloadURL());
} catch (final BrowserException e) {
if (br.getHttpConnection() != null && br.getHttpConnection().getResponseCode() == 502) {
link.getLinkStatus().setStatusText("We are sorry, but HellSpy is unavailable in your country");
return AvailableStatus.UNCHECKABLE;
}
}
if (br.containsHTML(">Soubor nenalezen<") || br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
filename = br.getRegex("<h1 title=\"([^<>\"]*?)\"").getMatch(0);
if (br.containsHTML(HTML_IS_STREAM)) {
/* Force extension */
ext = ".mp4";
} else {
/* Filesize is only given for non-streams */
filesize = br.getRegex("<span class=\"filesize right\">(\\d+(?:\\.\\d+)? <span>[^<>\"]*?)</span>").getMatch(0);
if (filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
filename = Encoding.htmlDecode(filename).trim();
if (ext != null) {
filename += ext;
}
link.setFinalFileName(filename);
if (filesize != null) {
filesize = filesize.replace("<span>", "");
link.setDownloadSize(SizeFormatter.getSize(filesize.replace(" ", "")));
}
return AvailableStatus.TRUE;
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return FREE_MAXDOWNLOADS;
}
@Override
public int getMaxSimultanPremiumDownloadNum() {
return ACCOUNT_PREMIUM_MAXDOWNLOADS;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
int maxchunks = FREE_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellShare is unavailable in your country", 4 * 60 * 60 * 1000l);
}
dllink = checkDirectLink(downloadLink, "free_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
/* No handling available for file links yet as all of them seem to be premium only! */
}
}
if (dllink == null && ALL_PREMIUMONLY) {
try {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
} catch (final Throwable e) {
if (e instanceof PluginException) {
throw (PluginException) e;
}
}
throw new PluginException(LinkStatus.ERROR_FATAL, "This file can only be downloaded by premium users");
}
br.setFollowRedirects(true);
br.setReadTimeout(120 * 1000);
/* Resume & unlimited chunks is definitly possible for stream links! */
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, FREE_RESUME, maxchunks);
if (!dl.getConnection().isContentDisposition()) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("Received html code insted of file");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("free_directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = openConnection(br2, dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@SuppressWarnings("deprecation")
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
int maxchunks = ACCOUNT_PREMIUM_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellSpy is unavailable in your country", 4 * 60 * 60 * 1000l);
}
login(account, false);
br.getPage(downloadLink.getDownloadURL());
dllink = checkDirectLink(downloadLink, "account_premium_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
final String filedownloadbutton = br.getURL() + "?download=1&iframe_view=popup+download_iframe_detail_popup";
URLConnectionAdapter con = openConnection(this.br, filedownloadbutton);
if (con.getContentType().contains("html")) {
br.followConnection();
dllink = br.getRegex("launchFullDownload\\(\\'(http[^<>\"]*?)\\'\\);\"").getMatch(0);
} else {
dllink = filedownloadbutton;
}
try {
con.disconnect();
} catch (final Throwable e) {
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dllink = dllink.replaceAll("\\\\", "");
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, ACCOUNT_PREMIUM_RESUME, maxchunks);
if (dl.getConnection().getResponseCode() == 503) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "Connection limit reached, please contact our support!", 5 * 60 * 1000l);
}
if (dl.getConnection().getContentType().contains("html")) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("The final dllink seems not to be a file!");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("account_premium_directlink", dllink);
dl.startDownload();
}
private String getStreamDirectlink() throws PluginException, IOException {
String play_url = br.getRegex("\"(/[^<>\"]*?do=play)\"").getMatch(0);
if (play_url == null) {
logger.warning("Stream-play-url is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
play_url = Encoding.htmlDecode(play_url);
this.br.getPage(play_url);
this.br.getRequest().setHtmlCode(br.toString().replace("\\", ""));
String dllink = br.getRegex("url: \"(http://stream\\d+\\.helldata\\.com[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
logger.warning("Stream-finallink is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
return dllink;
}
/** TODO: Maybe add support for time-accounts */
@SuppressWarnings("deprecation")
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
try {
login(account, true);
} catch (final PluginException e) {
ai.setStatus("Login failed");
account.setValid(false);
throw e;
}
br.getPage("/ucet/");
String traffic_left = br.getRegex("<td>Zakoupený:</td><td>(\\d+ MB)</td>").getMatch(0);
if (traffic_left == null) {
traffic_left = br.getRegex("<strong>Kreditů: </strong>([^<>\"]*?) \\– <a").getMatch(0);
}
if (traffic_left == null) {
ai.setStatus("Invalid/Unknown");
account.setValid(false);
return ai;
}
ai.setTrafficLeft(SizeFormatter.getSize(traffic_left));
ai.setValidUntil(-1);
ai.setStatus("Account with credits");
account.setProperty("free", false);
return ai;
}
@SuppressWarnings("unchecked")
public void login(final Account account, final boolean force) throws Exception {
synchronized (LOCK) {
try {
/* Load cookies */
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
boolean acmatch = Encoding.urlEncode(account.getUser()).equals(account.getStringProperty("name", Encoding.urlEncode(account.getUser())));
if (acmatch) {
acmatch = Encoding.urlEncode(account.getPass()).equals(account.getStringProperty("pass", Encoding.urlEncode(account.getPass())));
}
if (acmatch && ret != null && ret instanceof HashMap<?, ?> && !force) {
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(COOKIE_HOST, key, value);
}
return;
}
}
setBrowserExclusive();
br.setFollowRedirects(true);
br.setDebug(true);
br.getPage("http://www.hellspy.cz/?do=loginBox-loginpopup");
String login_action = br.getRegex("\"(http://(?:www\\.)?hell\\-share\\.com/user/login/\\?do=apiLoginForm-submit[^<>\"]*?)\"").getMatch(0);
if (login_action == null) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin defekt, bitte den JDownloader Support kontaktieren!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłąd wtyczki, skontaktuj się z Supportem JDownloadera!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin broken, please contact the JDownloader Support!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
login_action = Encoding.htmlDecode(login_action);
br.postPage(login_action, "username=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()) + "&permanent_login=on&submit_login=P%C5%99ihl%C3%A1sit+se&login=1&redir_url=http%3A%2F%2Fwww.hellspy.cz%2F%3Fdo%3DloginBox-login");
String permLogin = br.getCookie(br.getURL(), "permlogin");
if (permLogin == null || br.containsHTML("zadal jsi špatné uživatelské")) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername, Passwort oder login Captcha!\r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen? Versuche folgendes:\r\n1. Falls dein Passwort Sonderzeichen enthält, ändere es (entferne diese) und versuche es erneut!\r\n2. Gib deine Zugangsdaten per Hand (ohne kopieren/einfügen) ein.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędny użytkownik/hasło lub kod Captcha wymagany do zalogowania!\r\nUpewnij się, że prawidłowo wprowadziłes hasło i nazwę użytkownika. Dodatkowo:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź hasło i nazwę użytkownika ręcznie bez użycia opcji Kopiuj i Wklej.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or login captcha!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
/* Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(COOKIE_HOST);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
private URLConnectionAdapter openConnection(final Browser br, final String directlink) throws IOException {
URLConnectionAdapter con;
con = br.openGetConnection(directlink);
return con;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
return false;
}
} |
645_18 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Browser.BrowserException;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "hellspy.cz" }, urls = { "https?://(www\\.|porn\\.)?hellspy\\.(cz|com|sk)/(soutez/|sutaz/)?[a-z0-9\\-]+/\\d+" })
public class HellSpyCz extends PluginForHost {
/*
* Sister sites: hellshare.cz, (and their other domains), hellspy.cz (and their other domains), using same dataservers but slightly
* different script
*/
/* Connection stuff */
private static final boolean FREE_RESUME = true;
private static final int FREE_MAXCHUNKS = -5;
private static final int FREE_MAXDOWNLOADS = 20;
// private static final boolean ACCOUNT_FREE_RESUME = true;
// private static final int ACCOUNT_FREE_MAXCHUNKS = 0;
// private static final int ACCOUNT_FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_PREMIUM_RESUME = true;
private static final int ACCOUNT_PREMIUM_MAXCHUNKS = -5;
private static final int ACCOUNT_PREMIUM_MAXDOWNLOADS = 20;
private static final String COOKIE_HOST = "http://hellspy.cz";
private static final boolean ALL_PREMIUMONLY = true;
private static final String HTML_IS_STREAM = "section\\-videodetail\"";
private static Object LOCK = new Object();
public HellSpyCz(final PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://www.en.hellshare.com/register");
/* Especially for premium - don't make too many requests in a short time or we'll get 503 responses. */
this.setStartIntervall(2000l);
}
@Override
public String getAGBLink() {
return "http://www.en.hellshare.com/terms";
}
@SuppressWarnings("deprecation")
@Override
public void correctDownloadLink(final DownloadLink link) throws Exception {
final String linkpart = new Regex(link.getDownloadURL(), "hellspy.(cz|com|sk)/(.+)").getMatch(1);
link.setUrlDownload("http://www.hellspy.cz/" + linkpart);
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
String filename = null;
String ext = null;
String filesize = null;
setBrowserExclusive();
br.setCustomCharset("utf-8");
br.getHeaders().put("Accept-Language", "en-gb;q=0.9, en;q=0.8");
br.setFollowRedirects(true);
this.br.setDebug(true);
try {
br.getPage(link.getDownloadURL());
} catch (final BrowserException e) {
if (br.getHttpConnection() != null && br.getHttpConnection().getResponseCode() == 502) {
link.getLinkStatus().setStatusText("We are sorry, but HellSpy is unavailable in your country");
return AvailableStatus.UNCHECKABLE;
}
}
if (br.containsHTML(">Soubor nenalezen<") || br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
filename = br.getRegex("<h1 title=\"([^<>\"]*?)\"").getMatch(0);
if (br.containsHTML(HTML_IS_STREAM)) {
/* Force extension */
ext = ".mp4";
} else {
/* Filesize is only given for non-streams */
filesize = br.getRegex("<span class=\"filesize right\">(\\d+(?:\\.\\d+)? <span>[^<>\"]*?)</span>").getMatch(0);
if (filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
filename = Encoding.htmlDecode(filename).trim();
if (ext != null) {
filename += ext;
}
link.setFinalFileName(filename);
if (filesize != null) {
filesize = filesize.replace("<span>", "");
link.setDownloadSize(SizeFormatter.getSize(filesize.replace(" ", "")));
}
return AvailableStatus.TRUE;
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return FREE_MAXDOWNLOADS;
}
@Override
public int getMaxSimultanPremiumDownloadNum() {
return ACCOUNT_PREMIUM_MAXDOWNLOADS;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
int maxchunks = FREE_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellShare is unavailable in your country", 4 * 60 * 60 * 1000l);
}
dllink = checkDirectLink(downloadLink, "free_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
/* No handling available for file links yet as all of them seem to be premium only! */
}
}
if (dllink == null && ALL_PREMIUMONLY) {
try {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
} catch (final Throwable e) {
if (e instanceof PluginException) {
throw (PluginException) e;
}
}
throw new PluginException(LinkStatus.ERROR_FATAL, "This file can only be downloaded by premium users");
}
br.setFollowRedirects(true);
br.setReadTimeout(120 * 1000);
/* Resume & unlimited chunks is definitly possible for stream links! */
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, FREE_RESUME, maxchunks);
if (!dl.getConnection().isContentDisposition()) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("Received html code insted of file");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("free_directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = openConnection(br2, dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@SuppressWarnings("deprecation")
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
int maxchunks = ACCOUNT_PREMIUM_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellSpy is unavailable in your country", 4 * 60 * 60 * 1000l);
}
login(account, false);
br.getPage(downloadLink.getDownloadURL());
dllink = checkDirectLink(downloadLink, "account_premium_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
final String filedownloadbutton = br.getURL() + "?download=1&iframe_view=popup+download_iframe_detail_popup";
URLConnectionAdapter con = openConnection(this.br, filedownloadbutton);
if (con.getContentType().contains("html")) {
br.followConnection();
dllink = br.getRegex("launchFullDownload\\(\\'(http[^<>\"]*?)\\'\\);\"").getMatch(0);
} else {
dllink = filedownloadbutton;
}
try {
con.disconnect();
} catch (final Throwable e) {
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dllink = dllink.replaceAll("\\\\", "");
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, ACCOUNT_PREMIUM_RESUME, maxchunks);
if (dl.getConnection().getResponseCode() == 503) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "Connection limit reached, please contact our support!", 5 * 60 * 1000l);
}
if (dl.getConnection().getContentType().contains("html")) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("The final dllink seems not to be a file!");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("account_premium_directlink", dllink);
dl.startDownload();
}
private String getStreamDirectlink() throws PluginException, IOException {
String play_url = br.getRegex("\"(/[^<>\"]*?do=play)\"").getMatch(0);
if (play_url == null) {
logger.warning("Stream-play-url is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
play_url = Encoding.htmlDecode(play_url);
this.br.getPage(play_url);
this.br.getRequest().setHtmlCode(br.toString().replace("\\", ""));
String dllink = br.getRegex("url: \"(http://stream\\d+\\.helldata\\.com[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
logger.warning("Stream-finallink is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
return dllink;
}
/** TODO: Maybe add support for time-accounts */
@SuppressWarnings("deprecation")
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
try {
login(account, true);
} catch (final PluginException e) {
ai.setStatus("Login failed");
account.setValid(false);
throw e;
}
br.getPage("/ucet/");
String traffic_left = br.getRegex("<td>Zakoupený:</td><td>(\\d+ MB)</td>").getMatch(0);
if (traffic_left == null) {
traffic_left = br.getRegex("<strong>Kreditů: </strong>([^<>\"]*?) \\– <a").getMatch(0);
}
if (traffic_left == null) {
ai.setStatus("Invalid/Unknown");
account.setValid(false);
return ai;
}
ai.setTrafficLeft(SizeFormatter.getSize(traffic_left));
ai.setValidUntil(-1);
ai.setStatus("Account with credits");
account.setProperty("free", false);
return ai;
}
@SuppressWarnings("unchecked")
public void login(final Account account, final boolean force) throws Exception {
synchronized (LOCK) {
try {
/* Load cookies */
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
boolean acmatch = Encoding.urlEncode(account.getUser()).equals(account.getStringProperty("name", Encoding.urlEncode(account.getUser())));
if (acmatch) {
acmatch = Encoding.urlEncode(account.getPass()).equals(account.getStringProperty("pass", Encoding.urlEncode(account.getPass())));
}
if (acmatch && ret != null && ret instanceof HashMap<?, ?> && !force) {
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(COOKIE_HOST, key, value);
}
return;
}
}
setBrowserExclusive();
br.setFollowRedirects(true);
br.setDebug(true);
br.getPage("http://www.hellspy.cz/?do=loginBox-loginpopup");
String login_action = br.getRegex("\"(http://(?:www\\.)?hell\\-share\\.com/user/login/\\?do=apiLoginForm-submit[^<>\"]*?)\"").getMatch(0);
if (login_action == null) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin defekt, bitte den JDownloader Support kontaktieren!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłąd wtyczki, skontaktuj się z Supportem JDownloadera!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin broken, please contact the JDownloader Support!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
login_action = Encoding.htmlDecode(login_action);
br.postPage(login_action, "username=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()) + "&permanent_login=on&submit_login=P%C5%99ihl%C3%A1sit+se&login=1&redir_url=http%3A%2F%2Fwww.hellspy.cz%2F%3Fdo%3DloginBox-login");
String permLogin = br.getCookie(br.getURL(), "permlogin");
if (permLogin == null || br.containsHTML("zadal jsi špatné uživatelské")) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername, Passwort oder login Captcha!\r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen? Versuche folgendes:\r\n1. Falls dein Passwort Sonderzeichen enthält, ändere es (entferne diese) und versuche es erneut!\r\n2. Gib deine Zugangsdaten per Hand (ohne kopieren/einfügen) ein.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędny użytkownik/hasło lub kod Captcha wymagany do zalogowania!\r\nUpewnij się, że prawidłowo wprowadziłes hasło i nazwę użytkownika. Dodatkowo:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź hasło i nazwę użytkownika ręcznie bez użycia opcji Kopiuj i Wklej.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or login captcha!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
/* Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(COOKIE_HOST);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
private URLConnectionAdapter openConnection(final Browser br, final String directlink) throws IOException {
URLConnectionAdapter con;
con = br.openGetConnection(directlink);
return con;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
return false;
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/HellSpyCz.java | 5,847 | //www.hellspy.cz/" + linkpart);
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Browser.BrowserException;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "hellspy.cz" }, urls = { "https?://(www\\.|porn\\.)?hellspy\\.(cz|com|sk)/(soutez/|sutaz/)?[a-z0-9\\-]+/\\d+" })
public class HellSpyCz extends PluginForHost {
/*
* Sister sites: hellshare.cz, (and their other domains), hellspy.cz (and their other domains), using same dataservers but slightly
* different script
*/
/* Connection stuff */
private static final boolean FREE_RESUME = true;
private static final int FREE_MAXCHUNKS = -5;
private static final int FREE_MAXDOWNLOADS = 20;
// private static final boolean ACCOUNT_FREE_RESUME = true;
// private static final int ACCOUNT_FREE_MAXCHUNKS = 0;
// private static final int ACCOUNT_FREE_MAXDOWNLOADS = 20;
private static final boolean ACCOUNT_PREMIUM_RESUME = true;
private static final int ACCOUNT_PREMIUM_MAXCHUNKS = -5;
private static final int ACCOUNT_PREMIUM_MAXDOWNLOADS = 20;
private static final String COOKIE_HOST = "http://hellspy.cz";
private static final boolean ALL_PREMIUMONLY = true;
private static final String HTML_IS_STREAM = "section\\-videodetail\"";
private static Object LOCK = new Object();
public HellSpyCz(final PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://www.en.hellshare.com/register");
/* Especially for premium - don't make too many requests in a short time or we'll get 503 responses. */
this.setStartIntervall(2000l);
}
@Override
public String getAGBLink() {
return "http://www.en.hellshare.com/terms";
}
@SuppressWarnings("deprecation")
@Override
public void correctDownloadLink(final DownloadLink link) throws Exception {
final String linkpart = new Regex(link.getDownloadURL(), "hellspy.(cz|com|sk)/(.+)").getMatch(1);
link.setUrlDownload("http://www.hellspy.cz/" + <SUF>
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
String filename = null;
String ext = null;
String filesize = null;
setBrowserExclusive();
br.setCustomCharset("utf-8");
br.getHeaders().put("Accept-Language", "en-gb;q=0.9, en;q=0.8");
br.setFollowRedirects(true);
this.br.setDebug(true);
try {
br.getPage(link.getDownloadURL());
} catch (final BrowserException e) {
if (br.getHttpConnection() != null && br.getHttpConnection().getResponseCode() == 502) {
link.getLinkStatus().setStatusText("We are sorry, but HellSpy is unavailable in your country");
return AvailableStatus.UNCHECKABLE;
}
}
if (br.containsHTML(">Soubor nenalezen<") || br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
filename = br.getRegex("<h1 title=\"([^<>\"]*?)\"").getMatch(0);
if (br.containsHTML(HTML_IS_STREAM)) {
/* Force extension */
ext = ".mp4";
} else {
/* Filesize is only given for non-streams */
filesize = br.getRegex("<span class=\"filesize right\">(\\d+(?:\\.\\d+)? <span>[^<>\"]*?)</span>").getMatch(0);
if (filesize == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
filename = Encoding.htmlDecode(filename).trim();
if (ext != null) {
filename += ext;
}
link.setFinalFileName(filename);
if (filesize != null) {
filesize = filesize.replace("<span>", "");
link.setDownloadSize(SizeFormatter.getSize(filesize.replace(" ", "")));
}
return AvailableStatus.TRUE;
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return FREE_MAXDOWNLOADS;
}
@Override
public int getMaxSimultanPremiumDownloadNum() {
return ACCOUNT_PREMIUM_MAXDOWNLOADS;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
int maxchunks = FREE_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellShare is unavailable in your country", 4 * 60 * 60 * 1000l);
}
dllink = checkDirectLink(downloadLink, "free_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
/* No handling available for file links yet as all of them seem to be premium only! */
}
}
if (dllink == null && ALL_PREMIUMONLY) {
try {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
} catch (final Throwable e) {
if (e instanceof PluginException) {
throw (PluginException) e;
}
}
throw new PluginException(LinkStatus.ERROR_FATAL, "This file can only be downloaded by premium users");
}
br.setFollowRedirects(true);
br.setReadTimeout(120 * 1000);
/* Resume & unlimited chunks is definitly possible for stream links! */
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, FREE_RESUME, maxchunks);
if (!dl.getConnection().isContentDisposition()) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("Received html code insted of file");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("free_directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = openConnection(br2, dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@SuppressWarnings("deprecation")
@Override
public void handlePremium(final DownloadLink downloadLink, final Account account) throws Exception {
int maxchunks = ACCOUNT_PREMIUM_MAXCHUNKS;
String dllink = null;
requestFileInformation(downloadLink);
if (br.getHttpConnection().getResponseCode() == 502) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "We are sorry, but HellSpy is unavailable in your country", 4 * 60 * 60 * 1000l);
}
login(account, false);
br.getPage(downloadLink.getDownloadURL());
dllink = checkDirectLink(downloadLink, "account_premium_directlink");
if (dllink == null) {
if (br.containsHTML(HTML_IS_STREAM)) {
dllink = getStreamDirectlink();
/* No chunklimit for streams */
maxchunks = 0;
} else {
final String filedownloadbutton = br.getURL() + "?download=1&iframe_view=popup+download_iframe_detail_popup";
URLConnectionAdapter con = openConnection(this.br, filedownloadbutton);
if (con.getContentType().contains("html")) {
br.followConnection();
dllink = br.getRegex("launchFullDownload\\(\\'(http[^<>\"]*?)\\'\\);\"").getMatch(0);
} else {
dllink = filedownloadbutton;
}
try {
con.disconnect();
} catch (final Throwable e) {
}
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dllink = dllink.replaceAll("\\\\", "");
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, ACCOUNT_PREMIUM_RESUME, maxchunks);
if (dl.getConnection().getResponseCode() == 503) {
throw new PluginException(LinkStatus.ERROR_HOSTER_TEMPORARILY_UNAVAILABLE, "Connection limit reached, please contact our support!", 5 * 60 * 1000l);
}
if (dl.getConnection().getContentType().contains("html")) {
if (dl.getConnection().getResponseCode() == 403) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 403", 60 * 60 * 1000l);
} else if (dl.getConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error 404", 60 * 60 * 1000l);
}
logger.warning("The final dllink seems not to be a file!");
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("account_premium_directlink", dllink);
dl.startDownload();
}
private String getStreamDirectlink() throws PluginException, IOException {
String play_url = br.getRegex("\"(/[^<>\"]*?do=play)\"").getMatch(0);
if (play_url == null) {
logger.warning("Stream-play-url is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
play_url = Encoding.htmlDecode(play_url);
this.br.getPage(play_url);
this.br.getRequest().setHtmlCode(br.toString().replace("\\", ""));
String dllink = br.getRegex("url: \"(http://stream\\d+\\.helldata\\.com[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
logger.warning("Stream-finallink is null");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
return dllink;
}
/** TODO: Maybe add support for time-accounts */
@SuppressWarnings("deprecation")
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
try {
login(account, true);
} catch (final PluginException e) {
ai.setStatus("Login failed");
account.setValid(false);
throw e;
}
br.getPage("/ucet/");
String traffic_left = br.getRegex("<td>Zakoupený:</td><td>(\\d+ MB)</td>").getMatch(0);
if (traffic_left == null) {
traffic_left = br.getRegex("<strong>Kreditů: </strong>([^<>\"]*?) \\– <a").getMatch(0);
}
if (traffic_left == null) {
ai.setStatus("Invalid/Unknown");
account.setValid(false);
return ai;
}
ai.setTrafficLeft(SizeFormatter.getSize(traffic_left));
ai.setValidUntil(-1);
ai.setStatus("Account with credits");
account.setProperty("free", false);
return ai;
}
@SuppressWarnings("unchecked")
public void login(final Account account, final boolean force) throws Exception {
synchronized (LOCK) {
try {
/* Load cookies */
br.setCookiesExclusive(true);
final Object ret = account.getProperty("cookies", null);
boolean acmatch = Encoding.urlEncode(account.getUser()).equals(account.getStringProperty("name", Encoding.urlEncode(account.getUser())));
if (acmatch) {
acmatch = Encoding.urlEncode(account.getPass()).equals(account.getStringProperty("pass", Encoding.urlEncode(account.getPass())));
}
if (acmatch && ret != null && ret instanceof HashMap<?, ?> && !force) {
final HashMap<String, String> cookies = (HashMap<String, String>) ret;
if (account.isValid()) {
for (final Map.Entry<String, String> cookieEntry : cookies.entrySet()) {
final String key = cookieEntry.getKey();
final String value = cookieEntry.getValue();
this.br.setCookie(COOKIE_HOST, key, value);
}
return;
}
}
setBrowserExclusive();
br.setFollowRedirects(true);
br.setDebug(true);
br.getPage("http://www.hellspy.cz/?do=loginBox-loginpopup");
String login_action = br.getRegex("\"(http://(?:www\\.)?hell\\-share\\.com/user/login/\\?do=apiLoginForm-submit[^<>\"]*?)\"").getMatch(0);
if (login_action == null) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin defekt, bitte den JDownloader Support kontaktieren!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłąd wtyczki, skontaktuj się z Supportem JDownloadera!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlugin broken, please contact the JDownloader Support!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
login_action = Encoding.htmlDecode(login_action);
br.postPage(login_action, "username=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()) + "&permanent_login=on&submit_login=P%C5%99ihl%C3%A1sit+se&login=1&redir_url=http%3A%2F%2Fwww.hellspy.cz%2F%3Fdo%3DloginBox-login");
String permLogin = br.getCookie(br.getURL(), "permlogin");
if (permLogin == null || br.containsHTML("zadal jsi špatné uživatelské")) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername, Passwort oder login Captcha!\r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen? Versuche folgendes:\r\n1. Falls dein Passwort Sonderzeichen enthält, ändere es (entferne diese) und versuche es erneut!\r\n2. Gib deine Zugangsdaten per Hand (ohne kopieren/einfügen) ein.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędny użytkownik/hasło lub kod Captcha wymagany do zalogowania!\r\nUpewnij się, że prawidłowo wprowadziłes hasło i nazwę użytkownika. Dodatkowo:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź hasło i nazwę użytkownika ręcznie bez użycia opcji Kopiuj i Wklej.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or login captcha!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
/* Save cookies */
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(COOKIE_HOST);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
private URLConnectionAdapter openConnection(final Browser br, final String directlink) throws IOException {
URLConnectionAdapter con;
con = br.openGetConnection(directlink);
return con;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
/* NO OVERRIDE!! We need to stay 0.9*compatible */
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
return false;
}
} |
656_0 | package com.qcadoo.mes.productionCounting.listeners;
import com.qcadoo.mes.productionCounting.constants.ParameterFieldsPC;
import com.qcadoo.mes.productionCounting.constants.PriceBasedOn;
import com.qcadoo.mes.productionCounting.constants.ReceiptOfProducts;
import com.qcadoo.mes.productionCounting.constants.ReleaseOfMaterials;
import com.qcadoo.view.api.ComponentState;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.CheckBoxComponent;
import com.qcadoo.view.api.components.FieldComponent;
import org.springframework.stereotype.Service;
@Service
public class ProductionCountingParametersListeners {
/**
* Cena PW na podst.:
*
* parametr aktywny, gdy Przyjęcie wyrobów = na zakończeniu zlecenia. Wówczas użytkownik może wybrać, czy chce przyjmować wg kosztu nominalnego, czy rzeczywistego TKW
*
* gdy Przyjęcie wyrobów <> na zakończeniu zlecenia, to parametr ustawiony jako Koszt nominalny produktu i nie można go zmienić
*/
public void onReceiptOfProductsChange(final ViewDefinitionState view, final ComponentState state, final String[] args) {
FieldComponent priceBasedOn = (FieldComponent) view.getComponentByReference(ParameterFieldsPC.PRICE_BASED_ON);
FieldComponent receiptOfProducts = (FieldComponent) view.getComponentByReference(ParameterFieldsPC.RECEIPT_OF_PRODUCTS);
if (ReceiptOfProducts.END_OF_THE_ORDER.getStringValue()
.equals(receiptOfProducts.getFieldValue().toString())) {
priceBasedOn.setEnabled(true);
} else {
priceBasedOn.setEnabled(false);
priceBasedOn.setFieldValue(PriceBasedOn.NOMINAL_PRODUCT_COST.getStringValue());
}
}
public void onReleaseOfMaterialsChange(final ViewDefinitionState view, final ComponentState state, final String[] args) {
CheckBoxComponent consumptionOfRawMaterialsBasedOnStandards = (CheckBoxComponent) view
.getComponentByReference(ParameterFieldsPC.CONSUMPTION_OF_RAW_MATERIALS_BASED_ON_STANDARDS);
FieldComponent releaseOfMaterials = (FieldComponent) view.getComponentByReference(ParameterFieldsPC.RELEASE_OF_MATERIALS);
if (ReleaseOfMaterials.MANUALLY_TO_ORDER_OR_GROUP.getStringValue()
.equals(releaseOfMaterials.getFieldValue().toString())) {
consumptionOfRawMaterialsBasedOnStandards.setChecked(false);
consumptionOfRawMaterialsBasedOnStandards.setEnabled(false);
} else {
consumptionOfRawMaterialsBasedOnStandards.setEnabled(true);
}
}
}
| qcadoo/mes | mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/listeners/ProductionCountingParametersListeners.java | 783 | /**
* Cena PW na podst.:
*
* parametr aktywny, gdy Przyjęcie wyrobów = na zakończeniu zlecenia. Wówczas użytkownik może wybrać, czy chce przyjmować wg kosztu nominalnego, czy rzeczywistego TKW
*
* gdy Przyjęcie wyrobów <> na zakończeniu zlecenia, to parametr ustawiony jako Koszt nominalny produktu i nie można go zmienić
*/ | block_comment | pl | package com.qcadoo.mes.productionCounting.listeners;
import com.qcadoo.mes.productionCounting.constants.ParameterFieldsPC;
import com.qcadoo.mes.productionCounting.constants.PriceBasedOn;
import com.qcadoo.mes.productionCounting.constants.ReceiptOfProducts;
import com.qcadoo.mes.productionCounting.constants.ReleaseOfMaterials;
import com.qcadoo.view.api.ComponentState;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.CheckBoxComponent;
import com.qcadoo.view.api.components.FieldComponent;
import org.springframework.stereotype.Service;
@Service
public class ProductionCountingParametersListeners {
/**
* Cena PW na <SUF>*/
public void onReceiptOfProductsChange(final ViewDefinitionState view, final ComponentState state, final String[] args) {
FieldComponent priceBasedOn = (FieldComponent) view.getComponentByReference(ParameterFieldsPC.PRICE_BASED_ON);
FieldComponent receiptOfProducts = (FieldComponent) view.getComponentByReference(ParameterFieldsPC.RECEIPT_OF_PRODUCTS);
if (ReceiptOfProducts.END_OF_THE_ORDER.getStringValue()
.equals(receiptOfProducts.getFieldValue().toString())) {
priceBasedOn.setEnabled(true);
} else {
priceBasedOn.setEnabled(false);
priceBasedOn.setFieldValue(PriceBasedOn.NOMINAL_PRODUCT_COST.getStringValue());
}
}
public void onReleaseOfMaterialsChange(final ViewDefinitionState view, final ComponentState state, final String[] args) {
CheckBoxComponent consumptionOfRawMaterialsBasedOnStandards = (CheckBoxComponent) view
.getComponentByReference(ParameterFieldsPC.CONSUMPTION_OF_RAW_MATERIALS_BASED_ON_STANDARDS);
FieldComponent releaseOfMaterials = (FieldComponent) view.getComponentByReference(ParameterFieldsPC.RELEASE_OF_MATERIALS);
if (ReleaseOfMaterials.MANUALLY_TO_ORDER_OR_GROUP.getStringValue()
.equals(releaseOfMaterials.getFieldValue().toString())) {
consumptionOfRawMaterialsBasedOnStandards.setChecked(false);
consumptionOfRawMaterialsBasedOnStandards.setEnabled(false);
} else {
consumptionOfRawMaterialsBasedOnStandards.setEnabled(true);
}
}
}
|
665_13 | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.captcha.v2.challenge.recaptcha.v2.CaptchaHelperHostPluginRecaptchaV2;
import org.jdownloader.plugins.components.antiDDoSForHost;
import jd.PluginWrapper;
import jd.config.ConfigContainer;
import jd.config.ConfigEntry;
import jd.http.Browser;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.Account.AccountType;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.components.PluginJSonUtils;
import jd.utils.locale.JDL;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "mountfile.net" }, urls = { "https?://(www\\.)?mountfile\\.net/(?!d/)[A-Za-z0-9]+" })
public class MountFileNet extends antiDDoSForHost {
private final String MAINPAGE = "http://mountfile.net";
/* For reconnect special handling */
private static Object CTRLLOCK = new Object();
private final String EXPERIMENTALHANDLING = "EXPERIMENTALHANDLING";
private final String[] IPCHECK = new String[] { "http://ipcheck0.jdownloader.org", "http://ipcheck1.jdownloader.org", "http://ipcheck2.jdownloader.org", "http://ipcheck3.jdownloader.org" };
private static HashMap<String, Long> blockedIPsMap = new HashMap<String, Long>();
private static final String PROPERTY_LASTDOWNLOAD = "mountfilenet_lastdownload_timestamp";
private final String LASTIP = "LASTIP";
private static AtomicReference<String> lastIP = new AtomicReference<String>();
private static AtomicReference<String> currentIP = new AtomicReference<String>();
private final Pattern IPREGEX = Pattern.compile("(([1-2])?([0-9])?([0-9])\\.([1-2])?([0-9])?([0-9])\\.([1-2])?([0-9])?([0-9])\\.([1-2])?([0-9])?([0-9]))", Pattern.CASE_INSENSITIVE);
private static final long FREE_RECONNECTWAIT_GENERAL = 1 * 60 * 60 * 1000L;
public MountFileNet(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://mountfile.net/premium/");
}
@Override
public String getAGBLink() {
return "http://mountfile.net/terms/";
}
public boolean hasAutoCaptcha() {
return false;
}
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
return false;
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws Exception {
this.setBrowserExclusive();
br.setFollowRedirects(true);
getPage(link.getDownloadURL());
if (br.containsHTML(">File not found<") || br.getURL().equals("http://mountfile.net/")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final Regex fileInfo = br.getRegex("<h2 style=\"margin:0\">([^<>\"]*?)</h2>[\t\n\r ]+<div class=\"comment\">([^<>\"]*?)</div>");
final String filename = fileInfo.getMatch(0);
final String filesize = fileInfo.getMatch(1);
if (filename == null || filesize == null) {
if (!br.containsHTML("class=\"downloadPageTableV2\"")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(Encoding.htmlDecode(filename.trim()));
link.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@SuppressWarnings({ "deprecation", "unchecked" })
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
currentIP.set(this.getIP());
final boolean useExperimentalHandling = this.getPluginConfig().getBooleanProperty(this.EXPERIMENTALHANDLING, false);
long lastdownload = 0;
long passedTimeSinceLastDl = 0;
synchronized (CTRLLOCK) {
/* Load list of saved IPs + timestamp of last download */
final Object lastdownloadmap = this.getPluginConfig().getProperty(PROPERTY_LASTDOWNLOAD);
if (lastdownloadmap != null && lastdownloadmap instanceof HashMap && blockedIPsMap.isEmpty()) {
blockedIPsMap = (HashMap<String, Long>) lastdownloadmap;
}
}
if (useExperimentalHandling) {
/*
* If the user starts a download in free (unregistered) mode the waittime is on his IP. This also affects free accounts if he tries to start
* more downloads via free accounts afterwards BUT nontheless the limit is only on his IP so he CAN download using the same free accounts
* after performing a reconnect!
*/
lastdownload = getPluginSavedLastDownloadTimestamp();
passedTimeSinceLastDl = System.currentTimeMillis() - lastdownload;
if (passedTimeSinceLastDl < FREE_RECONNECTWAIT_GENERAL) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, FREE_RECONNECTWAIT_GENERAL - passedTimeSinceLastDl);
}
}
requestFileInformation(downloadLink);
postPage(br.getURL(), "free=Slow+download&hash=" + fid);
final long timeBefore = System.currentTimeMillis();
if (br.containsHTML("<div id=\"(\\w+)\".+grecaptcha\\.render\\(\\s*'\\1',")) {
final String recaptchaV2Response = new CaptchaHelperHostPluginRecaptchaV2(this, br).getToken();
waitTime(timeBefore, downloadLink);
postPage(br.getURL(), "free=Get+download+link&hash=" + fid + "&g-recaptcha-response=" + Encoding.urlEncode(recaptchaV2Response));
String reconnectWait = br.getRegex("You should wait (\\d+) minutes before downloading next file").getMatch(0);
if (reconnectWait == null) {
reconnectWait = br.getRegex("Please wait (\\d+) minutes before downloading next file or").getMatch(0);
}
if (reconnectWait != null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, Integer.parseInt(reconnectWait) * 60 * 1001l);
}
if (br.containsHTML(">Sorry, you have reached a download limit for today \\([\\w \\.]+\\)\\. Please wait for tomorrow")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Reached the download limit!", 60 * 60 * 1000l);
}
}
String dllink = br.getRegex("\"(https?://d\\d+\\.mountfile.net/[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
dllink = br.getRegex("<div style=\"margin: 10px auto 20px\" class=\"center\">[\t\n\r ]+<a href=\"(http://[^<>\"]*?)\"").getMatch(0);
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("not found")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error", 10 * 60 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
blockedIPsMap.put(currentIP.get(), System.currentTimeMillis());
getPluginConfig().setProperty(PROPERTY_LASTDOWNLOAD, blockedIPsMap);
try {
this.setIP(currentIP.get(), downloadLink);
} catch (final Throwable e) {
}
dl.startDownload();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
private void waitTime(long timeBefore, final DownloadLink downloadLink) throws PluginException {
int passedTime = (int) ((System.currentTimeMillis() - timeBefore) / 1000) - 1;
/** Ticket Time */
int wait = 60;
final String ttt = br.getRegex("var sec = (\\d+)").getMatch(0);
if (ttt != null) {
wait = Integer.parseInt(ttt);
}
wait -= passedTime;
if (wait > 0) {
sleep(wait * 1000l, downloadLink);
}
}
private static final Object LOCK = new Object();
private void login(Account account, boolean force) throws Exception {
synchronized (LOCK) {
try {
// Load cookies
br.setCookiesExclusive(true);
final Cookies cookies = account.loadCookies("");
if (cookies != null) {
this.br.setCookies(this.getHost(), cookies);
this.br.getPage("https://" + this.getHost() + "/");
if (this.br.containsHTML("account/logout/")) {
return;
}
this.br = new Browser();
}
br.setFollowRedirects(true);
getPage("https://" + this.getHost() + "/account/login/");
String postData = "url=http%253A%252F%252Fmountfile.net%252F&send=sign+in&email=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass());
final String captchaurl = this.br.getRegex("(/captcha/\\?\\d+)").getMatch(0);
if (captchaurl != null) {
final DownloadLink dummyLink = new DownloadLink(this, "Account", this.getHost(), "http://" + this.getHost(), true);
final String c = getCaptchaCode(captchaurl, dummyLink);
postData += "&captcha=" + Encoding.urlEncode(c);
}
postPage("/account/login", postData);
if (br.getCookie(MAINPAGE, "usid") == null) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername, Passwort oder login Captcha!\r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen? Versuche folgendes:\r\n1. Falls dein Passwort Sonderzeichen enthält, ändere es (entferne diese) und versuche es erneut!\r\n2. Gib deine Zugangsdaten per Hand (ohne kopieren/einfügen) ein.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędny użytkownik/hasło lub kod Captcha wymagany do zalogowania!\r\nUpewnij się, że prawidłowo wprowadziłes hasło i nazwę użytkownika. Dodatkowo:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź hasło i nazwę użytkownika ręcznie bez użycia opcji Kopiuj i Wklej.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or login captcha!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
account.saveCookies(this.br.getCookies(this.getHost()), "");
} catch (final PluginException e) {
account.clearCookies("");
throw e;
}
}
}
@SuppressWarnings("deprecation")
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
if (!account.getUser().matches(".+@.+\\..+")) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBitte gib deine E-Mail Adresse ins Benutzername Feld ein!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlease enter your e-mail adress in the username field!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
try {
login(account, true);
} catch (final PluginException e) {
account.setValid(false);
throw e;
}
String expire = br.getRegex("premium till (\\d{2}/\\d{2}/\\d{2})").getMatch(0);
if (expire == null) {
expire = br.getRegex("premium till ([A-Za-z]+ \\d{1,2}, \\d{4})").getMatch(0);
}
final boolean is_premium_without_expiredate = br.containsHTML("eternal premium");
if (!is_premium_without_expiredate && expire == null) {
account.setType(AccountType.FREE);
ai.setStatus("Free Account");
} else {
if (expire != null && expire.matches("\\d{2}/\\d{2}/\\d{2}")) {
ai.setValidUntil(TimeFormatter.getMilliSeconds(expire, "MM/dd/yy", Locale.ENGLISH));
} else if (expire != null) {
/* New 2016-10-19 */
ai.setValidUntil(TimeFormatter.getMilliSeconds(expire, "MMMM dd, yyyy", Locale.ENGLISH));
}
ai.setUnlimitedTraffic();
account.setValid(true);
account.setType(AccountType.PREMIUM);
ai.setStatus("Premium User");
}
return ai;
}
@SuppressWarnings("deprecation")
@Override
public void handlePremium(final DownloadLink link, final Account account) throws Exception {
if (account.getType() == AccountType.FREE) {
login(account, false);
handleFree(link);
} else {
requestFileInformation(link);
login(account, false);
/* First check if user has direct download enabled. */
dl = new jd.plugins.BrowserAdapter().openDownload(br, link, link.getDownloadURL(), true, 0);
if (!dl.getConnection().isContentDisposition()) {
/* No direct download? Manually get directurl ... */
br.followConnection();
errorhandlingPremium();
br.getHeaders().put("Accept", "application/json, text/javascript, */*; q=0.01");
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
postPage("/load/premium/", "js=1&hash=" + new Regex(link.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0));
errorhandlingPremium();
String dllink = PluginJSonUtils.getJsonValue(this.br, "ok");
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, link, dllink, true, 0);
if (!dl.getConnection().isContentDisposition()) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
}
private void errorhandlingPremium() throws PluginException {
if (this.br.containsHTML("you have reached a download limit for today")) {
/* 2015-09-15: daily downloadlimit = 20 GB */
logger.info("Daily downloadlimit reached");
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
}
if (br.containsHTML("File was deleted by owner or due to a violation of service rules")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
@Override
public int getMaxSimultanPremiumDownloadNum() {
return -1;
}
@Override
protected boolean useRUA() {
return true;
}
/* Stuff for special reconnect errorhandling */
private String getIP() throws PluginException {
final Browser ip = new Browser();
String currentIP = null;
final ArrayList<String> checkIP = new ArrayList<String>(Arrays.asList(this.IPCHECK));
Collections.shuffle(checkIP);
for (final String ipServer : checkIP) {
if (currentIP == null) {
try {
ip.getPage(ipServer);
currentIP = ip.getRegex(this.IPREGEX).getMatch(0);
if (currentIP != null) {
break;
}
} catch (final Throwable e) {
}
}
}
if (currentIP == null) {
this.logger.warning("firewall/antivirus/malware/peerblock software is most likely is restricting accesss to JDownloader IP checking services");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
return currentIP;
}
private boolean ipChanged(final String IP, final DownloadLink link) throws PluginException {
String currentIP = null;
if (IP != null && new Regex(IP, this.IPREGEX).matches()) {
currentIP = IP;
} else {
currentIP = this.getIP();
}
if (currentIP == null) {
return false;
}
String lastIP = link.getStringProperty(this.LASTIP, null);
if (lastIP == null) {
lastIP = MountFileNet.lastIP.get();
}
return !currentIP.equals(lastIP);
}
private boolean setIP(final String IP, final DownloadLink link) throws PluginException {
synchronized (this.IPCHECK) {
if (IP != null && !new Regex(IP, this.IPREGEX).matches()) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
if (this.ipChanged(IP, link) == false) {
// Static IP or failure to reconnect! We don't change lastIP
this.logger.warning("Your IP hasn't changed since last download");
return false;
} else {
final String lastIP = IP;
link.setProperty(this.LASTIP, lastIP);
MountFileNet.lastIP.set(lastIP);
this.logger.info("LastIP = " + lastIP);
return true;
}
}
}
private long getPluginSavedLastDownloadTimestamp() {
long lastdownload = 0;
synchronized (blockedIPsMap) {
final Iterator<Entry<String, Long>> it = blockedIPsMap.entrySet().iterator();
while (it.hasNext()) {
final Entry<String, Long> ipentry = it.next();
final String ip = ipentry.getKey();
final long timestamp = ipentry.getValue();
if (System.currentTimeMillis() - timestamp >= FREE_RECONNECTWAIT_GENERAL) {
/* Remove old entries */
it.remove();
}
if (ip.equals(currentIP.get())) {
lastdownload = timestamp;
}
}
}
return lastdownload;
}
private void setConfigElements() {
this.getConfig().addEntry(new ConfigEntry(ConfigContainer.TYPE_CHECKBOX, this.getPluginConfig(), this.EXPERIMENTALHANDLING, JDL.L("plugins.hoster.mountfilenet.useExperimentalWaittimeHandling", "Activate experimental waittime handling to prevent additional captchas?")).setDefaultValue(false));
}
private static AtomicReference<String> userAgent = new AtomicReference<String>(null);
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | substanc3-dev/jdownloader2 | src/jd/plugins/hoster/MountFileNet.java | 6,283 | //ipcheck0.jdownloader.org", "http://ipcheck1.jdownloader.org", "http://ipcheck2.jdownloader.org", "http://ipcheck3.jdownloader.org" };
| line_comment | pl | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program 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.
//
//This program 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 jd.plugins.hoster;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.captcha.v2.challenge.recaptcha.v2.CaptchaHelperHostPluginRecaptchaV2;
import org.jdownloader.plugins.components.antiDDoSForHost;
import jd.PluginWrapper;
import jd.config.ConfigContainer;
import jd.config.ConfigEntry;
import jd.http.Browser;
import jd.http.Cookies;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.Account.AccountType;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.components.PluginJSonUtils;
import jd.utils.locale.JDL;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "mountfile.net" }, urls = { "https?://(www\\.)?mountfile\\.net/(?!d/)[A-Za-z0-9]+" })
public class MountFileNet extends antiDDoSForHost {
private final String MAINPAGE = "http://mountfile.net";
/* For reconnect special handling */
private static Object CTRLLOCK = new Object();
private final String EXPERIMENTALHANDLING = "EXPERIMENTALHANDLING";
private final String[] IPCHECK = new String[] { "http://ipcheck0.jdownloader.org", "http://ipcheck1.jdownloader.org", <SUF>
private static HashMap<String, Long> blockedIPsMap = new HashMap<String, Long>();
private static final String PROPERTY_LASTDOWNLOAD = "mountfilenet_lastdownload_timestamp";
private final String LASTIP = "LASTIP";
private static AtomicReference<String> lastIP = new AtomicReference<String>();
private static AtomicReference<String> currentIP = new AtomicReference<String>();
private final Pattern IPREGEX = Pattern.compile("(([1-2])?([0-9])?([0-9])\\.([1-2])?([0-9])?([0-9])\\.([1-2])?([0-9])?([0-9])\\.([1-2])?([0-9])?([0-9]))", Pattern.CASE_INSENSITIVE);
private static final long FREE_RECONNECTWAIT_GENERAL = 1 * 60 * 60 * 1000L;
public MountFileNet(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium("http://mountfile.net/premium/");
}
@Override
public String getAGBLink() {
return "http://mountfile.net/terms/";
}
public boolean hasAutoCaptcha() {
return false;
}
public boolean hasCaptcha(DownloadLink link, jd.plugins.Account acc) {
if (acc == null) {
/* no account, yes we can expect captcha */
return true;
}
if (Boolean.TRUE.equals(acc.getBooleanProperty("free"))) {
/* free accounts also have captchas */
return true;
}
return false;
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws Exception {
this.setBrowserExclusive();
br.setFollowRedirects(true);
getPage(link.getDownloadURL());
if (br.containsHTML(">File not found<") || br.getURL().equals("http://mountfile.net/")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final Regex fileInfo = br.getRegex("<h2 style=\"margin:0\">([^<>\"]*?)</h2>[\t\n\r ]+<div class=\"comment\">([^<>\"]*?)</div>");
final String filename = fileInfo.getMatch(0);
final String filesize = fileInfo.getMatch(1);
if (filename == null || filesize == null) {
if (!br.containsHTML("class=\"downloadPageTableV2\"")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(Encoding.htmlDecode(filename.trim()));
link.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@SuppressWarnings({ "deprecation", "unchecked" })
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
currentIP.set(this.getIP());
final boolean useExperimentalHandling = this.getPluginConfig().getBooleanProperty(this.EXPERIMENTALHANDLING, false);
long lastdownload = 0;
long passedTimeSinceLastDl = 0;
synchronized (CTRLLOCK) {
/* Load list of saved IPs + timestamp of last download */
final Object lastdownloadmap = this.getPluginConfig().getProperty(PROPERTY_LASTDOWNLOAD);
if (lastdownloadmap != null && lastdownloadmap instanceof HashMap && blockedIPsMap.isEmpty()) {
blockedIPsMap = (HashMap<String, Long>) lastdownloadmap;
}
}
if (useExperimentalHandling) {
/*
* If the user starts a download in free (unregistered) mode the waittime is on his IP. This also affects free accounts if he tries to start
* more downloads via free accounts afterwards BUT nontheless the limit is only on his IP so he CAN download using the same free accounts
* after performing a reconnect!
*/
lastdownload = getPluginSavedLastDownloadTimestamp();
passedTimeSinceLastDl = System.currentTimeMillis() - lastdownload;
if (passedTimeSinceLastDl < FREE_RECONNECTWAIT_GENERAL) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, FREE_RECONNECTWAIT_GENERAL - passedTimeSinceLastDl);
}
}
requestFileInformation(downloadLink);
postPage(br.getURL(), "free=Slow+download&hash=" + fid);
final long timeBefore = System.currentTimeMillis();
if (br.containsHTML("<div id=\"(\\w+)\".+grecaptcha\\.render\\(\\s*'\\1',")) {
final String recaptchaV2Response = new CaptchaHelperHostPluginRecaptchaV2(this, br).getToken();
waitTime(timeBefore, downloadLink);
postPage(br.getURL(), "free=Get+download+link&hash=" + fid + "&g-recaptcha-response=" + Encoding.urlEncode(recaptchaV2Response));
String reconnectWait = br.getRegex("You should wait (\\d+) minutes before downloading next file").getMatch(0);
if (reconnectWait == null) {
reconnectWait = br.getRegex("Please wait (\\d+) minutes before downloading next file or").getMatch(0);
}
if (reconnectWait != null) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, Integer.parseInt(reconnectWait) * 60 * 1001l);
}
if (br.containsHTML(">Sorry, you have reached a download limit for today \\([\\w \\.]+\\)\\. Please wait for tomorrow")) {
throw new PluginException(LinkStatus.ERROR_IP_BLOCKED, "Reached the download limit!", 60 * 60 * 1000l);
}
}
String dllink = br.getRegex("\"(https?://d\\d+\\.mountfile.net/[^<>\"]*?)\"").getMatch(0);
if (dllink == null) {
dllink = br.getRegex("<div style=\"margin: 10px auto 20px\" class=\"center\">[\t\n\r ]+<a href=\"(http://[^<>\"]*?)\"").getMatch(0);
}
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("not found")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Server error", 10 * 60 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
blockedIPsMap.put(currentIP.get(), System.currentTimeMillis());
getPluginConfig().setProperty(PROPERTY_LASTDOWNLOAD, blockedIPsMap);
try {
this.setIP(currentIP.get(), downloadLink);
} catch (final Throwable e) {
}
dl.startDownload();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 1;
}
private void waitTime(long timeBefore, final DownloadLink downloadLink) throws PluginException {
int passedTime = (int) ((System.currentTimeMillis() - timeBefore) / 1000) - 1;
/** Ticket Time */
int wait = 60;
final String ttt = br.getRegex("var sec = (\\d+)").getMatch(0);
if (ttt != null) {
wait = Integer.parseInt(ttt);
}
wait -= passedTime;
if (wait > 0) {
sleep(wait * 1000l, downloadLink);
}
}
private static final Object LOCK = new Object();
private void login(Account account, boolean force) throws Exception {
synchronized (LOCK) {
try {
// Load cookies
br.setCookiesExclusive(true);
final Cookies cookies = account.loadCookies("");
if (cookies != null) {
this.br.setCookies(this.getHost(), cookies);
this.br.getPage("https://" + this.getHost() + "/");
if (this.br.containsHTML("account/logout/")) {
return;
}
this.br = new Browser();
}
br.setFollowRedirects(true);
getPage("https://" + this.getHost() + "/account/login/");
String postData = "url=http%253A%252F%252Fmountfile.net%252F&send=sign+in&email=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass());
final String captchaurl = this.br.getRegex("(/captcha/\\?\\d+)").getMatch(0);
if (captchaurl != null) {
final DownloadLink dummyLink = new DownloadLink(this, "Account", this.getHost(), "http://" + this.getHost(), true);
final String c = getCaptchaCode(captchaurl, dummyLink);
postData += "&captcha=" + Encoding.urlEncode(c);
}
postPage("/account/login", postData);
if (br.getCookie(MAINPAGE, "usid") == null) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nUngültiger Benutzername, Passwort oder login Captcha!\r\nDu bist dir sicher, dass dein eingegebener Benutzername und Passwort stimmen? Versuche folgendes:\r\n1. Falls dein Passwort Sonderzeichen enthält, ändere es (entferne diese) und versuche es erneut!\r\n2. Gib deine Zugangsdaten per Hand (ohne kopieren/einfügen) ein.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("pl".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBłędny użytkownik/hasło lub kod Captcha wymagany do zalogowania!\r\nUpewnij się, że prawidłowo wprowadziłes hasło i nazwę użytkownika. Dodatkowo:\r\n1. Jeśli twoje hasło zawiera znaki specjalne, zmień je (usuń) i spróbuj ponownie!\r\n2. Wprowadź hasło i nazwę użytkownika ręcznie bez użycia opcji Kopiuj i Wklej.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nInvalid username/password or login captcha!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
account.saveCookies(this.br.getCookies(this.getHost()), "");
} catch (final PluginException e) {
account.clearCookies("");
throw e;
}
}
}
@SuppressWarnings("deprecation")
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
final AccountInfo ai = new AccountInfo();
if (!account.getUser().matches(".+@.+\\..+")) {
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nBitte gib deine E-Mail Adresse ins Benutzername Feld ein!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nPlease enter your e-mail adress in the username field!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
}
try {
login(account, true);
} catch (final PluginException e) {
account.setValid(false);
throw e;
}
String expire = br.getRegex("premium till (\\d{2}/\\d{2}/\\d{2})").getMatch(0);
if (expire == null) {
expire = br.getRegex("premium till ([A-Za-z]+ \\d{1,2}, \\d{4})").getMatch(0);
}
final boolean is_premium_without_expiredate = br.containsHTML("eternal premium");
if (!is_premium_without_expiredate && expire == null) {
account.setType(AccountType.FREE);
ai.setStatus("Free Account");
} else {
if (expire != null && expire.matches("\\d{2}/\\d{2}/\\d{2}")) {
ai.setValidUntil(TimeFormatter.getMilliSeconds(expire, "MM/dd/yy", Locale.ENGLISH));
} else if (expire != null) {
/* New 2016-10-19 */
ai.setValidUntil(TimeFormatter.getMilliSeconds(expire, "MMMM dd, yyyy", Locale.ENGLISH));
}
ai.setUnlimitedTraffic();
account.setValid(true);
account.setType(AccountType.PREMIUM);
ai.setStatus("Premium User");
}
return ai;
}
@SuppressWarnings("deprecation")
@Override
public void handlePremium(final DownloadLink link, final Account account) throws Exception {
if (account.getType() == AccountType.FREE) {
login(account, false);
handleFree(link);
} else {
requestFileInformation(link);
login(account, false);
/* First check if user has direct download enabled. */
dl = new jd.plugins.BrowserAdapter().openDownload(br, link, link.getDownloadURL(), true, 0);
if (!dl.getConnection().isContentDisposition()) {
/* No direct download? Manually get directurl ... */
br.followConnection();
errorhandlingPremium();
br.getHeaders().put("Accept", "application/json, text/javascript, */*; q=0.01");
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
postPage("/load/premium/", "js=1&hash=" + new Regex(link.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0));
errorhandlingPremium();
String dllink = PluginJSonUtils.getJsonValue(this.br, "ok");
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl = new jd.plugins.BrowserAdapter().openDownload(br, link, dllink, true, 0);
if (!dl.getConnection().isContentDisposition()) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl.startDownload();
}
}
private void errorhandlingPremium() throws PluginException {
if (this.br.containsHTML("you have reached a download limit for today")) {
/* 2015-09-15: daily downloadlimit = 20 GB */
logger.info("Daily downloadlimit reached");
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
}
if (br.containsHTML("File was deleted by owner or due to a violation of service rules")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
}
@Override
public int getMaxSimultanPremiumDownloadNum() {
return -1;
}
@Override
protected boolean useRUA() {
return true;
}
/* Stuff for special reconnect errorhandling */
private String getIP() throws PluginException {
final Browser ip = new Browser();
String currentIP = null;
final ArrayList<String> checkIP = new ArrayList<String>(Arrays.asList(this.IPCHECK));
Collections.shuffle(checkIP);
for (final String ipServer : checkIP) {
if (currentIP == null) {
try {
ip.getPage(ipServer);
currentIP = ip.getRegex(this.IPREGEX).getMatch(0);
if (currentIP != null) {
break;
}
} catch (final Throwable e) {
}
}
}
if (currentIP == null) {
this.logger.warning("firewall/antivirus/malware/peerblock software is most likely is restricting accesss to JDownloader IP checking services");
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
return currentIP;
}
private boolean ipChanged(final String IP, final DownloadLink link) throws PluginException {
String currentIP = null;
if (IP != null && new Regex(IP, this.IPREGEX).matches()) {
currentIP = IP;
} else {
currentIP = this.getIP();
}
if (currentIP == null) {
return false;
}
String lastIP = link.getStringProperty(this.LASTIP, null);
if (lastIP == null) {
lastIP = MountFileNet.lastIP.get();
}
return !currentIP.equals(lastIP);
}
private boolean setIP(final String IP, final DownloadLink link) throws PluginException {
synchronized (this.IPCHECK) {
if (IP != null && !new Regex(IP, this.IPREGEX).matches()) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
if (this.ipChanged(IP, link) == false) {
// Static IP or failure to reconnect! We don't change lastIP
this.logger.warning("Your IP hasn't changed since last download");
return false;
} else {
final String lastIP = IP;
link.setProperty(this.LASTIP, lastIP);
MountFileNet.lastIP.set(lastIP);
this.logger.info("LastIP = " + lastIP);
return true;
}
}
}
private long getPluginSavedLastDownloadTimestamp() {
long lastdownload = 0;
synchronized (blockedIPsMap) {
final Iterator<Entry<String, Long>> it = blockedIPsMap.entrySet().iterator();
while (it.hasNext()) {
final Entry<String, Long> ipentry = it.next();
final String ip = ipentry.getKey();
final long timestamp = ipentry.getValue();
if (System.currentTimeMillis() - timestamp >= FREE_RECONNECTWAIT_GENERAL) {
/* Remove old entries */
it.remove();
}
if (ip.equals(currentIP.get())) {
lastdownload = timestamp;
}
}
}
return lastdownload;
}
private void setConfigElements() {
this.getConfig().addEntry(new ConfigEntry(ConfigContainer.TYPE_CHECKBOX, this.getPluginConfig(), this.EXPERIMENTALHANDLING, JDL.L("plugins.hoster.mountfilenet.useExperimentalWaittimeHandling", "Activate experimental waittime handling to prevent additional captchas?")).setDefaultValue(false));
}
private static AtomicReference<String> userAgent = new AtomicReference<String>(null);
@Override
public void reset() {
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} |
924_0 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kamb3.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie niepoprawne. Zaklada, ze r_n=r_{n-2}=...=0 *
* jest warunkiem dostatecznym, zeby uklad byl przegrywajacy.*
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kamb3 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int x = 0;
int[] a;
if (n % 2 == 0) {
a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
} else {
a = new int[n+1];
a[0] = 0;
for (int j=1; j<=n; j++)
a[j] = readInt();
n++;
}
boolean wygra = false;
for (int j=0; j<n; j+=2) {
if (a[j] != a[j+1])
wygra = true;
}
System.out.println(wygra?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kamb3.java | 616 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kamb3.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie niepoprawne. Zaklada, ze r_n=r_{n-2}=...=0 *
* jest warunkiem dostatecznym, zeby uklad byl przegrywajacy.*
* *
* *
*************************************************************************/ | block_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna <SUF>*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kamb3 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int x = 0;
int[] a;
if (n % 2 == 0) {
a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
} else {
a = new int[n+1];
a[0] = 0;
for (int j=1; j<=n; j++)
a[j] = readInt();
n++;
}
boolean wygra = false;
for (int j=0; j<n; j+=2) {
if (a[j] != a[j+1])
wygra = true;
}
System.out.println(wygra?"TAK":"NIE");
}
}
};
|
924_1 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kamb3.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie niepoprawne. Zaklada, ze r_n=r_{n-2}=...=0 *
* jest warunkiem dostatecznym, zeby uklad byl przegrywajacy.*
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kamb3 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int x = 0;
int[] a;
if (n % 2 == 0) {
a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
} else {
a = new int[n+1];
a[0] = 0;
for (int j=1; j<=n; j++)
a[j] = readInt();
n++;
}
boolean wygra = false;
for (int j=0; j<n; j+=2) {
if (a[j] != a[j+1])
wygra = true;
}
System.out.println(wygra?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kamb3.java | 616 | // wczytuje jedna liczbe ze standardowego wejscia | line_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kamb3.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie niepoprawne. Zaklada, ze r_n=r_{n-2}=...=0 *
* jest warunkiem dostatecznym, zeby uklad byl przegrywajacy.*
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kamb3 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna <SUF>
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int x = 0;
int[] a;
if (n % 2 == 0) {
a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
} else {
a = new int[n+1];
a[0] = 0;
for (int j=1; j<=n; j++)
a[j] = readInt();
n++;
}
boolean wygra = false;
for (int j=0; j<n; j+=2) {
if (a[j] != a[j+1])
wygra = true;
}
System.out.println(wygra?"TAK":"NIE");
}
}
};
|
926_0 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams4.java | 690 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/ | block_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna <SUF>*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
926_1 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams4.java | 690 | // wczytuje jedna liczbe ze standardowego wejscia | line_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna <SUF>
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
926_2 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams4.java | 690 | // sprawcza czy zostaly jeszcze jakies kamienie | line_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy <SUF>
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
926_3 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams4.java | 690 | // zwraca 1 gdy dany stan jest wygrywajacy, 0 wpp | line_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams4.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze bez psamietywania *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class kams4 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
// zwraca 1 <SUF>
static boolean wygra(int[] v) {
if (koniec(v))
return false;
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (!wygra(v)) {
v[i] += k;
return true;
}
v[i] += k;
k--;
}
}
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
928_0 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true gdy dany stan jest wygrywajacy, false wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams5.java | 845 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/ | block_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna <SUF>*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true gdy dany stan jest wygrywajacy, false wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
928_1 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true gdy dany stan jest wygrywajacy, false wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams5.java | 845 | // wczytuje jedna liczbe ze standardowego wejscia | line_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna <SUF>
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true gdy dany stan jest wygrywajacy, false wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
928_2 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true gdy dany stan jest wygrywajacy, false wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams5.java | 845 | // sprawcza czy zostaly jeszcze jakies kamienie | line_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy <SUF>
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true gdy dany stan jest wygrywajacy, false wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
928_3 | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true gdy dany stan jest wygrywajacy, false wpp
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2009/code/kam/prog/kams5.java | 845 | // zwraca true gdy dany stan jest wygrywajacy, false wpp | line_comment | pl | /*************************************************************************
* *
* XVI Olimpiada Informatyczna *
* *
* Zadanie: Kamyki (KAM) *
* Plik: kams5.java *
* Autor: Szymon Wrzyszcz *
* Opis: Rozwiazanie wykladnicze uzywajace programowania *
* dynamicznego *
* *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.HashMap;
public class kams5 {
private static BufferedReader bufReader;
private static StringTokenizer tokenizer;
// wczytuje jedna liczbe ze standardowego wejscia
static int readInt() throws java.io.IOException {
if (tokenizer.hasMoreTokens() == false)
tokenizer = new StringTokenizer(bufReader.readLine());
return Integer.parseInt(tokenizer.nextToken());
}
// sprawcza czy zostaly jeszcze jakies kamienie
static boolean koniec(int[] v) {
for (int i=0; i<v.length; i++)
if (v[i] > 0)
return false;
return true;
}
static HashMap M;
static String serializuj(int[] v) {
String s = "";
for (int i=0; i<v.length; i++)
s += v[i] + " ";
return s;
}
// zwraca true <SUF>
static boolean wygra(int[] v) {
if (koniec(v))
return false;
String s = serializuj(v);
if (M.containsKey(s))
return M.get(s).equals(true);
for (int i=0; i<v.length; i++) {
int k = (i==0)?(v[0]):(v[i]-v[i-1]);
while (k >= 1) {
v[i] -= k;
if (wygra(v) == false) {
v[i] += k;
M.put(serializuj(v), true);
return true;
}
v[i] += k;
k--;
}
}
M.put(serializuj(v), false);
return false;
}
public static void main(String[] args) throws java.io.IOException {
bufReader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer(bufReader.readLine());
int u = readInt();
for (int i=0; i<u; i++) {
int n = readInt();
int[] a = new int[n];
for (int j=0; j<n; j++)
a[j] = readInt();
M = new HashMap();
System.out.println(wygra(a)?"TAK":"NIE");
}
}
};
|
932_0 | package w2.zadania.hjxxzk;
import java.util.Scanner;
public class Zadanie7 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = 0, sum = 0, i = -1; //zakładam, że liczba poniżej 100 nie jest wliczana do średniej
do {
sum += num;
++i;
System.out.println("Podaj liczbę: ");
num = scanner.nextInt();
} while(num > 100);
if(i == 0)
System.out.println("Nie podano liczby spełniającej wymagania");
else
System.out.println("Średnia z podanych liczb wynosi: " + ((double)sum/i));
}
}
| WebAce-Group/java101-edycja1 | w2/zadania/hjxxzk/Zadanie7.java | 234 | //zakładam, że liczba poniżej 100 nie jest wliczana do średniej | line_comment | pl | package w2.zadania.hjxxzk;
import java.util.Scanner;
public class Zadanie7 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = 0, sum = 0, i = -1; //zakładam, że <SUF>
do {
sum += num;
++i;
System.out.println("Podaj liczbę: ");
num = scanner.nextInt();
} while(num > 100);
if(i == 0)
System.out.println("Nie podano liczby spełniającej wymagania");
else
System.out.println("Średnia z podanych liczb wynosi: " + ((double)sum/i));
}
}
|
937_0 | import java.util.Scanner;
// Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi,
// czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić,
// czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku,
// gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat.
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} | WebAce-Group/java101-edycja1 | w2/zadania/KropaPL/Zadanie3.java | 607 | // Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi, | line_comment | pl | import java.util.Scanner;
// Napisz program, <SUF>
// czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić,
// czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku,
// gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat.
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} |
937_1 | import java.util.Scanner;
// Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi,
// czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić,
// czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku,
// gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat.
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} | WebAce-Group/java101-edycja1 | w2/zadania/KropaPL/Zadanie3.java | 607 | // czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić, | line_comment | pl | import java.util.Scanner;
// Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi,
// czy da <SUF>
// czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku,
// gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat.
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} |
937_2 | import java.util.Scanner;
// Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi,
// czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić,
// czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku,
// gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat.
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} | WebAce-Group/java101-edycja1 | w2/zadania/KropaPL/Zadanie3.java | 607 | // czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku, | line_comment | pl | import java.util.Scanner;
// Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi,
// czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić,
// czy trójkąt <SUF>
// gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat.
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} |
937_3 | import java.util.Scanner;
// Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi,
// czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić,
// czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku,
// gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat.
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} | WebAce-Group/java101-edycja1 | w2/zadania/KropaPL/Zadanie3.java | 607 | // gdy trójkąt nie da się zbudować, program powinien wyświetlić odpowiedni komunikat. | line_comment | pl | import java.util.Scanner;
// Napisz program, który pobierze od użytkownika 3 całkowite boki trójkąta i sprawdzi,
// czy da się z nich zbudować trójkąt. Jeśli da się, to program powinien sprawdzić,
// czy trójkąt jest równoboczny, równoramienny czy różnoboczny. W przypadku,
// gdy trójkąt <SUF>
public class Zadanie3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Test na istnienie trójkąta");
double[] boki = new double[3];
for (int i = 0; i < boki.length; i++){
System.out.println("Wprowadź " + (i+1) + ". bok: ");
boki [i] = scan.nextDouble();
}
boolean test = trojkat(boki[0], boki[1], boki[2]);
System.out.println("Wynik testu to: " + test);
if (test) {
System.out.println("Trójkąt jest: " + typ(boki[0], boki[1], boki[2]));
} else {
System.out.println("Z tych odcinków nie da się zbudować trójkąta");
}
}
private static boolean trojkat(double a, double b, double c) {
boolean test = false;
if (a >= b && a >= c && (a < b + c)) {
test = true;
} else if (b >= a && b >= c && (b < a + c)) {
test = true;
} else if (c >= a && c >= b && (c < a + b)) {
test = true;
}
return test;
}
private static String typ(double a, double b, double c){
if (a == b && a == c ) {
return "równoboczny";
} else if ((a == b && a != c) || (b == c && b != a)) {
return "równoramienny";
} else {
return "różnoramienny";
}
}
} |
944_3 | import volume.GaussianDerivative;
import volume.Kernel1D;
import bijnum.BIJmatrix;
public class MyGabor {
public static Feature[] filter(float image[], float mask[], int width, float scales[])
{
int nrOrders = 3;
Feature ls[][][] = new Feature[scales.length][nrOrders][];
float thetas[][] = new float[nrOrders][];
int length = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
thetas[order] = thetaSet(order);
ls[j][order] = L(image, mask, width, order, scales[j], thetas[order]);
length += ls[j][order].length;
}
}
Feature Ln[] = new Feature[length];
int index = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
for(int i = 0; i < ls[j][order].length; i++)
Ln[index++] = ls[j][order][i];
}
}
ls = (Feature[][][])null;
return Ln;
}
public static float[] thetaSet(int order)
{
float theta[] = new float[order + 1];
theta[0] = 0.0F;
if(order == 1)
theta[1] = 90F;
else
if(order == 2)
{
theta[1] = 60F;
theta[2] = 120F;
} else
if(order != 0)
throw new IllegalArgumentException("order > 2");
return theta;
}
protected static String name(int order, double scale, double theta, String extraText)
{
if(order == 0)
return extraText + "L" + order + " scale=" + scale + "p";
else
return extraText + "L" + order + "(" + theta + " dgrs) scale=" + scale + "p";
}
public static Feature[] L(float image[], float mask[], int width, int n, double scale, float theta[])
{
Feature f[] = new Feature[theta.length];
float L[][] = new float[theta.length][];
if(n == 0)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
L[0] = convolvex(image, mask, width, image.length / width, k0);
L[0] = convolvey(L[0], width, image.length / width, k0);
f[0] = new Feature(name(n, scale, 0.0D, ""), L[0]);
} else
if(n == 1)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
float Lx[] = convolvex(image, mask, width, image.length / width, k1);
Lx = convolvey(Lx, width, image.length / width, k0);
float Ly[] = convolvex(image, mask, width, image.length / width, k0);
Ly = convolvey(Ly, width, image.length / width, k1);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
float px[] = new float[Lx.length];
BIJmatrix.mulElements(px, Lx, cth);
float py[] = new float[Lx.length];
BIJmatrix.mulElements(py, Ly, sth);
L[i] = BIJmatrix.addElements(px, py);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
} else
if(n == 2)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
volume.Kernel1D k2 = new GaussianDerivative(scale, 2);
float Lxx[] = convolvex(image, mask, width, image.length / width, k2);
Lxx = convolvey(Lxx, width, image.length / width, k0);
float Lxy[] = convolvex(image, mask, width, image.length / width, k1);
Lxy = convolvey(Lxy, width, image.length / width, k1);
float Lyy[] = convolvex(image, mask, width, image.length / width, k0);
Lyy = convolvey(Lyy, width, image.length / width, k2);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
double c2th = cth * cth;
double csth = cth * sth;
double s2th = sth * sth;
float pxx2[] = new float[Lxx.length];
BIJmatrix.mulElements(pxx2, Lxx, c2th);
float pxy2[] = new float[Lxy.length];
BIJmatrix.mulElements(pxy2, Lxy, 2D * csth);
float pyy2[] = new float[Lyy.length];
BIJmatrix.mulElements(pyy2, Lyy, s2th);
L[i] = BIJmatrix.addElements(pxx2, pxy2);
BIJmatrix.addElements(L[i], L[i], pyy2);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
}
return f;
}
/**
* Convolution of plane with 1D separated kernel along the x-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvex(float [] plane, float [] mask, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around x, convolve over -kernel.halfwidth .. x .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x+k;
int yi = y;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
if(mask[yi*width+xi]!=0) //sprawdzamy czy maska nie jest zerowa
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
/**
* Convolution of plane with 1D separated kernel along the y-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvey(float [] plane, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
// Convolve in y direction.
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around y, convolve over -kernel.halfwidth .. y .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x;
int yi = y+k;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
}
| bernii/IrisRecognition | src/MyGabor.java | 2,736 | //sprawdzamy czy maska nie jest zerowa
| line_comment | pl | import volume.GaussianDerivative;
import volume.Kernel1D;
import bijnum.BIJmatrix;
public class MyGabor {
public static Feature[] filter(float image[], float mask[], int width, float scales[])
{
int nrOrders = 3;
Feature ls[][][] = new Feature[scales.length][nrOrders][];
float thetas[][] = new float[nrOrders][];
int length = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
thetas[order] = thetaSet(order);
ls[j][order] = L(image, mask, width, order, scales[j], thetas[order]);
length += ls[j][order].length;
}
}
Feature Ln[] = new Feature[length];
int index = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
for(int i = 0; i < ls[j][order].length; i++)
Ln[index++] = ls[j][order][i];
}
}
ls = (Feature[][][])null;
return Ln;
}
public static float[] thetaSet(int order)
{
float theta[] = new float[order + 1];
theta[0] = 0.0F;
if(order == 1)
theta[1] = 90F;
else
if(order == 2)
{
theta[1] = 60F;
theta[2] = 120F;
} else
if(order != 0)
throw new IllegalArgumentException("order > 2");
return theta;
}
protected static String name(int order, double scale, double theta, String extraText)
{
if(order == 0)
return extraText + "L" + order + " scale=" + scale + "p";
else
return extraText + "L" + order + "(" + theta + " dgrs) scale=" + scale + "p";
}
public static Feature[] L(float image[], float mask[], int width, int n, double scale, float theta[])
{
Feature f[] = new Feature[theta.length];
float L[][] = new float[theta.length][];
if(n == 0)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
L[0] = convolvex(image, mask, width, image.length / width, k0);
L[0] = convolvey(L[0], width, image.length / width, k0);
f[0] = new Feature(name(n, scale, 0.0D, ""), L[0]);
} else
if(n == 1)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
float Lx[] = convolvex(image, mask, width, image.length / width, k1);
Lx = convolvey(Lx, width, image.length / width, k0);
float Ly[] = convolvex(image, mask, width, image.length / width, k0);
Ly = convolvey(Ly, width, image.length / width, k1);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
float px[] = new float[Lx.length];
BIJmatrix.mulElements(px, Lx, cth);
float py[] = new float[Lx.length];
BIJmatrix.mulElements(py, Ly, sth);
L[i] = BIJmatrix.addElements(px, py);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
} else
if(n == 2)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
volume.Kernel1D k2 = new GaussianDerivative(scale, 2);
float Lxx[] = convolvex(image, mask, width, image.length / width, k2);
Lxx = convolvey(Lxx, width, image.length / width, k0);
float Lxy[] = convolvex(image, mask, width, image.length / width, k1);
Lxy = convolvey(Lxy, width, image.length / width, k1);
float Lyy[] = convolvex(image, mask, width, image.length / width, k0);
Lyy = convolvey(Lyy, width, image.length / width, k2);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
double c2th = cth * cth;
double csth = cth * sth;
double s2th = sth * sth;
float pxx2[] = new float[Lxx.length];
BIJmatrix.mulElements(pxx2, Lxx, c2th);
float pxy2[] = new float[Lxy.length];
BIJmatrix.mulElements(pxy2, Lxy, 2D * csth);
float pyy2[] = new float[Lyy.length];
BIJmatrix.mulElements(pyy2, Lyy, s2th);
L[i] = BIJmatrix.addElements(pxx2, pxy2);
BIJmatrix.addElements(L[i], L[i], pyy2);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
}
return f;
}
/**
* Convolution of plane with 1D separated kernel along the x-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvex(float [] plane, float [] mask, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around x, convolve over -kernel.halfwidth .. x .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x+k;
int yi = y;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
if(mask[yi*width+xi]!=0) //sprawdzamy czy <SUF>
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
/**
* Convolution of plane with 1D separated kernel along the y-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvey(float [] plane, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
// Convolve in y direction.
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around y, convolve over -kernel.halfwidth .. y .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x;
int yi = y+k;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
}
|
948_0 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/ | block_comment | pl | /*************************************************************************
* *
* XV Olimpiada <SUF>*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_1 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | //reprezentacja grafu poprzez listy sasiedztwa | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu <SUF>
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_2 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | //liczba zablokowanych spotkan dla kazdego wierzcholka | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych <SUF>
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_3 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | //jako ktory dany wierzcholek zostal odwiedzony | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory <SUF>
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_4 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | //funkcja low dla kazdego wierzcholka | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low <SUF>
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_5 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | // czy dany wierzcholek jest punktem artykulacji? | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany <SUF>
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_6 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | // nr zablokowanego wierzcholka | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego <SUF>
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_7 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | //liczba krawedzi grafu | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi <SUF>
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_8 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | //dodanie nowej krawedzi nieskierowanej | line_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej <SUF>
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|
948_9 | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
| mostafa-saad/MyCompetitiveProgramming | Olympiad/POI/official/2008/code/blo/prog/blos6.java | 1,435 | /* przeszukiwanie w glab
* funkcja zwraca liczbe wierzcholkow z poddrzewa przeszukiwania*/ | block_comment | pl | /*************************************************************************
* *
* XV Olimpiada Informatyczna *
* *
* Zadanie: Blokada (BLO) *
* Plik: blos6.java *
* Autor: Marek Cygan, Marian Marek Kedzierski *
* Opis: Rozwiazanie nieoptymalne; implementacja w Javie. *
* *
*************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class blos6 {
public static int n; //liczba wierzcholkow
public static ArrayList<Integer>[] krawedzie; //reprezentacja grafu poprzez listy sasiedztwa
public static long[] blokada; //liczba zablokowanych spotkan dla kazdego wierzcholka
public static boolean[] odwiedzony;
public static int[] numer; //jako ktory dany wierzcholek zostal odwiedzony
public static int[] low; //funkcja low dla kazdego wierzcholka
public static int odwiedzone_wierzcholki;
public static boolean[] artyk; // czy dany wierzcholek jest punktem artykulacji?
public static int blocked; // nr zablokowanego wierzcholka
@SuppressWarnings("unchecked")
public static void WczytajGraf() throws java.io.IOException{
int m; //liczba krawedzi grafu
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tokenizer = new StringTokenizer(bufReader.readLine());
n = Integer.parseInt(tokenizer.nextToken());
m = Integer.parseInt(tokenizer.nextToken());
krawedzie = new ArrayList[n];
for (int i = 0; i < n; ++i) krawedzie[i] = new ArrayList<Integer>();
blokada = new long[n];
odwiedzony = new boolean[n];
numer = new int[n];
low = new int[n];
artyk = new boolean[n];
while (m-- > 0){
int a,b;
tokenizer = new StringTokenizer(bufReader.readLine());
a = Integer.parseInt(tokenizer.nextToken());
b = Integer.parseInt(tokenizer.nextToken());
//dodanie nowej krawedzi nieskierowanej
a--; b--;
krawedzie[a].add(b);
krawedzie[b].add(a);
}
}
/* przeszukiwanie w glab <SUF>*/
public static int Dfs(int x){
if (x == blocked) return 0;
odwiedzony[x] = true;
int my_size = 1;
for(Integer it : krawedzie[x])
if (!odwiedzony[it])
my_size += Dfs(it);
return my_size;
}
/* przeszukiwanie w glab wyznaczajace punkty artykulacji grafu */
public static void wyznacz_artyk(int x, int ojciec){
int liczba_odwiedzonych = 1;
int liczba_zablokowanych = 0;
odwiedzony[x] = true;
numer[x] = low[x] = odwiedzone_wierzcholki++;
for(Integer it : krawedzie[x])
if (!odwiedzony[it]){
wyznacz_artyk(it, x);
if (low[it] >= numer[x]){
artyk[x] = true;
} else{
low[x] = Math.min(low[x], low[it]);
}
} else if (it != ojciec) low[x] = Math.min(low[x], numer[it]);
}
public static void WypiszWynik(){
for (int i = 0; i < n; ++i) System.out.println(blokada[i]);
}
public static void main(String[] args) throws java.io.IOException {
new Thread(){
public void run(){
try{
int size;
WczytajGraf();
for (int i=0; i<n; ++i) odwiedzony[i] = false;
wyznacz_artyk(0, -1);
for (int v=0; v<n; ++v)
blokada[v] = 2 * (n - 1);
for (int v=0; v<n; ++v)
if (artyk[v]) {
for (int i=0; i<n; ++i) odwiedzony[i] = false;
blocked = v;
for (int i=0; i<n; ++i)
if (blocked != i && !odwiedzony[i]) {
size = Dfs(i);
blokada[v] += size * (n - 1 - size);
}
}
WypiszWynik();
} catch (IOException e){
}
}
}.start();
}
}
|