repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
games647/FastLogin | bukkit/src/main/java/com/github/games647/fastlogin/bukkit/event/BukkitFastLoginPremiumToggleEvent.java | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
| import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.event.FastLoginPremiumToggleEvent;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull; | /*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.event;
public class BukkitFastLoginPremiumToggleEvent extends Event implements FastLoginPremiumToggleEvent {
private static final HandlerList handlers = new HandlerList(); | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
// Path: bukkit/src/main/java/com/github/games647/fastlogin/bukkit/event/BukkitFastLoginPremiumToggleEvent.java
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.event.FastLoginPremiumToggleEvent;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.event;
public class BukkitFastLoginPremiumToggleEvent extends Event implements FastLoginPremiumToggleEvent {
private static final HandlerList handlers = new HandlerList(); | private final StoredProfile profile; |
games647/FastLogin | velocity/src/main/java/com/github/games647/fastlogin/velocity/event/VelocityFastLoginPreLoginEvent.java | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
//
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginPreLoginEvent.java
// public interface FastLoginPreLoginEvent {
//
// String getUsername();
// LoginSource getSource();
// StoredProfile getProfile();
// }
| import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSource;
import com.github.games647.fastlogin.core.shared.event.FastLoginPreLoginEvent; | /*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.velocity.event;
public class VelocityFastLoginPreLoginEvent implements FastLoginPreLoginEvent {
private final String username;
private final LoginSource source; | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
//
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginPreLoginEvent.java
// public interface FastLoginPreLoginEvent {
//
// String getUsername();
// LoginSource getSource();
// StoredProfile getProfile();
// }
// Path: velocity/src/main/java/com/github/games647/fastlogin/velocity/event/VelocityFastLoginPreLoginEvent.java
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSource;
import com.github.games647.fastlogin.core.shared.event.FastLoginPreLoginEvent;
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.velocity.event;
public class VelocityFastLoginPreLoginEvent implements FastLoginPreLoginEvent {
private final String username;
private final LoginSource source; | private final StoredProfile profile; |
games647/FastLogin | core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginPreLoginEvent.java | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
| import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSource; | /*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.core.shared.event;
public interface FastLoginPreLoginEvent {
String getUsername();
LoginSource getSource(); | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginPreLoginEvent.java
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSource;
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.core.shared.event;
public interface FastLoginPreLoginEvent {
String getUsername();
LoginSource getSource(); | StoredProfile getProfile(); |
games647/FastLogin | bukkit/src/main/java/com/github/games647/fastlogin/bukkit/event/BukkitFastLoginPreLoginEvent.java | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
//
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginPreLoginEvent.java
// public interface FastLoginPreLoginEvent {
//
// String getUsername();
// LoginSource getSource();
// StoredProfile getProfile();
// }
| import org.jetbrains.annotations.NotNull;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSource;
import com.github.games647.fastlogin.core.shared.event.FastLoginPreLoginEvent;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; | /*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.event;
public class BukkitFastLoginPreLoginEvent extends Event implements FastLoginPreLoginEvent {
private static final HandlerList handlers = new HandlerList();
private final String username;
private final LoginSource source; | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
//
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginPreLoginEvent.java
// public interface FastLoginPreLoginEvent {
//
// String getUsername();
// LoginSource getSource();
// StoredProfile getProfile();
// }
// Path: bukkit/src/main/java/com/github/games647/fastlogin/bukkit/event/BukkitFastLoginPreLoginEvent.java
import org.jetbrains.annotations.NotNull;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSource;
import com.github.games647.fastlogin.core.shared.event.FastLoginPreLoginEvent;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.event;
public class BukkitFastLoginPreLoginEvent extends Event implements FastLoginPreLoginEvent {
private static final HandlerList handlers = new HandlerList();
private final String username;
private final LoginSource source; | private final StoredProfile profile; |
games647/FastLogin | core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginAutoLoginEvent.java | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
| import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSession; | /*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.core.shared.event;
public interface FastLoginAutoLoginEvent extends FastLoginCancellableEvent {
LoginSession getSession(); | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginAutoLoginEvent.java
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSession;
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.core.shared.event;
public interface FastLoginAutoLoginEvent extends FastLoginCancellableEvent {
LoginSession getSession(); | StoredProfile getProfile(); |
games647/FastLogin | bukkit/src/main/java/com/github/games647/fastlogin/bukkit/event/BukkitFastLoginAutoLoginEvent.java | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
//
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginAutoLoginEvent.java
// public interface FastLoginAutoLoginEvent extends FastLoginCancellableEvent {
// LoginSession getSession();
// StoredProfile getProfile();
// }
| import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSession;
import com.github.games647.fastlogin.core.shared.event.FastLoginAutoLoginEvent;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; | /*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.event;
public class BukkitFastLoginAutoLoginEvent extends Event implements FastLoginAutoLoginEvent, Cancellable {
private static final HandlerList handlers = new HandlerList();
private final LoginSession session; | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
//
// Path: core/src/main/java/com/github/games647/fastlogin/core/shared/event/FastLoginAutoLoginEvent.java
// public interface FastLoginAutoLoginEvent extends FastLoginCancellableEvent {
// LoginSession getSession();
// StoredProfile getProfile();
// }
// Path: bukkit/src/main/java/com/github/games647/fastlogin/bukkit/event/BukkitFastLoginAutoLoginEvent.java
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSession;
import com.github.games647.fastlogin.core.shared.event.FastLoginAutoLoginEvent;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit.event;
public class BukkitFastLoginAutoLoginEvent extends Event implements FastLoginAutoLoginEvent, Cancellable {
private static final HandlerList handlers = new HandlerList();
private final LoginSession session; | private final StoredProfile profile; |
games647/FastLogin | bukkit/src/main/java/com/github/games647/fastlogin/bukkit/BukkitLoginSession.java | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
| import com.github.games647.craftapi.model.skin.SkinProperty;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSession;
import java.util.Optional; | /*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit;
/**
* Represents a client connecting to the server.
*
* This session is invalid if the player disconnects or the login was successful
*/
public class BukkitLoginSession extends LoginSession {
private static final byte[] EMPTY_ARRAY = {};
private final byte[] verifyToken;
private boolean verified;
private SkinProperty skinProperty;
public BukkitLoginSession(String username, byte[] verifyToken, boolean registered | // Path: core/src/main/java/com/github/games647/fastlogin/core/StoredProfile.java
// public class StoredProfile extends Profile {
//
// private long rowId;
// private final ReentrantLock saveLock = new ReentrantLock();
//
// private boolean premium;
// private String lastIp;
// private Instant lastLogin;
//
// public StoredProfile(long rowId, UUID uuid, String playerName, boolean premium, String lastIp, Instant lastLogin) {
// super(uuid, playerName);
//
// this.rowId = rowId;
// this.premium = premium;
// this.lastIp = lastIp;
// this.lastLogin = lastLogin;
// }
//
// public StoredProfile(UUID uuid, String playerName, boolean premium, String lastIp) {
// this(-1, uuid, playerName, premium, lastIp, Instant.now());
// }
//
// public ReentrantLock getSaveLock() {
// return saveLock;
// }
//
// public synchronized boolean isSaved() {
// return rowId >= 0;
// }
//
// public synchronized void setPlayerName(String playerName) {
// this.name = playerName;
// }
//
// public synchronized long getRowId() {
// return rowId;
// }
//
// public synchronized void setRowId(long generatedId) {
// this.rowId = generatedId;
// }
//
// // can be null
// public synchronized UUID getId() {
// return id;
// }
//
// public synchronized Optional<UUID> getOptId() {
// return Optional.ofNullable(id);
// }
//
// public synchronized void setId(UUID uniqueId) {
// this.id = uniqueId;
// }
//
// public synchronized boolean isPremium() {
// return premium;
// }
//
// public synchronized void setPremium(boolean premium) {
// this.premium = premium;
// }
//
// public synchronized String getLastIp() {
// return lastIp;
// }
//
// public synchronized void setLastIp(String lastIp) {
// this.lastIp = lastIp;
// }
//
// public synchronized Instant getLastLogin() {
// return lastLogin;
// }
//
// public synchronized void setLastLogin(Instant lastLogin) {
// this.lastLogin = lastLogin;
// }
//
// @Override
// public synchronized boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof StoredProfile)) return false;
// if (!super.equals(o)) return false;
// StoredProfile that = (StoredProfile) o;
// return rowId == that.rowId && premium == that.premium
// && Objects.equals(lastIp, that.lastIp) && lastLogin.equals(that.lastLogin);
// }
//
// @Override
// public synchronized int hashCode() {
// return Objects.hash(super.hashCode(), rowId, premium, lastIp, lastLogin);
// }
//
// @Override
// public synchronized String toString() {
// return this.getClass().getSimpleName() + '{' +
// "rowId=" + rowId +
// ", premium=" + premium +
// ", lastIp='" + lastIp + '\'' +
// ", lastLogin=" + lastLogin +
// "} " + super.toString();
// }
// }
// Path: bukkit/src/main/java/com/github/games647/fastlogin/bukkit/BukkitLoginSession.java
import com.github.games647.craftapi.model.skin.SkinProperty;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSession;
import java.util.Optional;
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2021 <Your name and contributors>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.bukkit;
/**
* Represents a client connecting to the server.
*
* This session is invalid if the player disconnects or the login was successful
*/
public class BukkitLoginSession extends LoginSession {
private static final byte[] EMPTY_ARRAY = {};
private final byte[] verifyToken;
private boolean verified;
private SkinProperty skinProperty;
public BukkitLoginSession(String username, byte[] verifyToken, boolean registered | , StoredProfile profile) { |
reines/httptunnel | src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelConfig.java | // Path: src/main/java/com/yammer/httptunnel/util/DefaultTunnelIdGenerator.java
// public class DefaultTunnelIdGenerator implements TunnelIdGenerator {
//
// private final SecureRandom generator;
//
// /**
// * Constructs a new instance using a new {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator() {
// this(new SecureRandom());
// }
//
// /**
// * Constructs a new instance using the provided {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator(SecureRandom generator) {
// this.generator = generator;
// }
//
// @Override
// public synchronized String generateId() {
// // synchronized to ensure that this code is thread safe. The Sun
// // standard implementations seem to be synchronized or lock free
// // but are not documented as guaranteeing this
// return Integer.toHexString(generator.nextInt());
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
| import java.util.Map;
import java.util.Map.Entry;
import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelConfig;
import com.yammer.httptunnel.util.DefaultTunnelIdGenerator;
import com.yammer.httptunnel.util.TunnelIdGenerator; | /*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.server;
/**
* Configuration for the server end of an HTTP tunnel. Any server socket channel
* properties set here will be applied uniformly to the underlying server
* channel, created from the channel factory provided to the
* {@link HttpTunnelServerChannelFactory}.
*/
public class HttpTunnelServerChannelConfig implements ServerSocketChannelConfig {
/**
* The default user-agent from which HTTP tunnel requests are allowed.
*/
public static final String DEFAULT_USER_AGENT = "HttpTunnel";
static final String USER_AGENT_OPTION = "userAgent";
static final String PIPELINE_FACTORY_OPTION = "pipelineFactory";
static final String TUNNEL_ID_GENERATOR_OPTION = "tunnelIdGenerator";
private static final String PROP_PKG = "org.jboss.netty.channel.socket.http.";
private static final String PROP_UserAgent = PROP_PKG + USER_AGENT_OPTION;
private String userAgent;
private ServerSocketChannel realChannel; | // Path: src/main/java/com/yammer/httptunnel/util/DefaultTunnelIdGenerator.java
// public class DefaultTunnelIdGenerator implements TunnelIdGenerator {
//
// private final SecureRandom generator;
//
// /**
// * Constructs a new instance using a new {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator() {
// this(new SecureRandom());
// }
//
// /**
// * Constructs a new instance using the provided {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator(SecureRandom generator) {
// this.generator = generator;
// }
//
// @Override
// public synchronized String generateId() {
// // synchronized to ensure that this code is thread safe. The Sun
// // standard implementations seem to be synchronized or lock free
// // but are not documented as guaranteeing this
// return Integer.toHexString(generator.nextInt());
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelConfig.java
import java.util.Map;
import java.util.Map.Entry;
import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelConfig;
import com.yammer.httptunnel.util.DefaultTunnelIdGenerator;
import com.yammer.httptunnel.util.TunnelIdGenerator;
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.server;
/**
* Configuration for the server end of an HTTP tunnel. Any server socket channel
* properties set here will be applied uniformly to the underlying server
* channel, created from the channel factory provided to the
* {@link HttpTunnelServerChannelFactory}.
*/
public class HttpTunnelServerChannelConfig implements ServerSocketChannelConfig {
/**
* The default user-agent from which HTTP tunnel requests are allowed.
*/
public static final String DEFAULT_USER_AGENT = "HttpTunnel";
static final String USER_AGENT_OPTION = "userAgent";
static final String PIPELINE_FACTORY_OPTION = "pipelineFactory";
static final String TUNNEL_ID_GENERATOR_OPTION = "tunnelIdGenerator";
private static final String PROP_PKG = "org.jboss.netty.channel.socket.http.";
private static final String PROP_UserAgent = PROP_PKG + USER_AGENT_OPTION;
private String userAgent;
private ServerSocketChannel realChannel; | private TunnelIdGenerator tunnelIdGenerator; |
reines/httptunnel | src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelConfig.java | // Path: src/main/java/com/yammer/httptunnel/util/DefaultTunnelIdGenerator.java
// public class DefaultTunnelIdGenerator implements TunnelIdGenerator {
//
// private final SecureRandom generator;
//
// /**
// * Constructs a new instance using a new {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator() {
// this(new SecureRandom());
// }
//
// /**
// * Constructs a new instance using the provided {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator(SecureRandom generator) {
// this.generator = generator;
// }
//
// @Override
// public synchronized String generateId() {
// // synchronized to ensure that this code is thread safe. The Sun
// // standard implementations seem to be synchronized or lock free
// // but are not documented as guaranteeing this
// return Integer.toHexString(generator.nextInt());
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
| import java.util.Map;
import java.util.Map.Entry;
import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelConfig;
import com.yammer.httptunnel.util.DefaultTunnelIdGenerator;
import com.yammer.httptunnel.util.TunnelIdGenerator; | /*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.server;
/**
* Configuration for the server end of an HTTP tunnel. Any server socket channel
* properties set here will be applied uniformly to the underlying server
* channel, created from the channel factory provided to the
* {@link HttpTunnelServerChannelFactory}.
*/
public class HttpTunnelServerChannelConfig implements ServerSocketChannelConfig {
/**
* The default user-agent from which HTTP tunnel requests are allowed.
*/
public static final String DEFAULT_USER_AGENT = "HttpTunnel";
static final String USER_AGENT_OPTION = "userAgent";
static final String PIPELINE_FACTORY_OPTION = "pipelineFactory";
static final String TUNNEL_ID_GENERATOR_OPTION = "tunnelIdGenerator";
private static final String PROP_PKG = "org.jboss.netty.channel.socket.http.";
private static final String PROP_UserAgent = PROP_PKG + USER_AGENT_OPTION;
private String userAgent;
private ServerSocketChannel realChannel;
private TunnelIdGenerator tunnelIdGenerator;
private ChannelPipelineFactory pipelineFactory;
HttpTunnelServerChannelConfig() {
userAgent = System.getProperty(PROP_UserAgent, DEFAULT_USER_AGENT);
realChannel = null; | // Path: src/main/java/com/yammer/httptunnel/util/DefaultTunnelIdGenerator.java
// public class DefaultTunnelIdGenerator implements TunnelIdGenerator {
//
// private final SecureRandom generator;
//
// /**
// * Constructs a new instance using a new {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator() {
// this(new SecureRandom());
// }
//
// /**
// * Constructs a new instance using the provided {@link SecureRandom} instance.
// */
// public DefaultTunnelIdGenerator(SecureRandom generator) {
// this.generator = generator;
// }
//
// @Override
// public synchronized String generateId() {
// // synchronized to ensure that this code is thread safe. The Sun
// // standard implementations seem to be synchronized or lock free
// // but are not documented as guaranteeing this
// return Integer.toHexString(generator.nextInt());
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelConfig.java
import java.util.Map;
import java.util.Map.Entry;
import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelConfig;
import com.yammer.httptunnel.util.DefaultTunnelIdGenerator;
import com.yammer.httptunnel.util.TunnelIdGenerator;
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.server;
/**
* Configuration for the server end of an HTTP tunnel. Any server socket channel
* properties set here will be applied uniformly to the underlying server
* channel, created from the channel factory provided to the
* {@link HttpTunnelServerChannelFactory}.
*/
public class HttpTunnelServerChannelConfig implements ServerSocketChannelConfig {
/**
* The default user-agent from which HTTP tunnel requests are allowed.
*/
public static final String DEFAULT_USER_AGENT = "HttpTunnel";
static final String USER_AGENT_OPTION = "userAgent";
static final String PIPELINE_FACTORY_OPTION = "pipelineFactory";
static final String TUNNEL_ID_GENERATOR_OPTION = "tunnelIdGenerator";
private static final String PROP_PKG = "org.jboss.netty.channel.socket.http.";
private static final String PROP_UserAgent = PROP_PKG + USER_AGENT_OPTION;
private String userAgent;
private ServerSocketChannel realChannel;
private TunnelIdGenerator tunnelIdGenerator;
private ChannelPipelineFactory pipelineFactory;
HttpTunnelServerChannelConfig() {
userAgent = System.getProperty(PROP_UserAgent, DEFAULT_USER_AGENT);
realChannel = null; | tunnelIdGenerator = new DefaultTunnelIdGenerator(); |
reines/httptunnel | src/test/java/com/yammer/httptunnel/WriteSplitterTest.java | // Path: src/main/java/com/yammer/httptunnel/util/WriteFragmenter.java
// public class WriteFragmenter extends SimpleChannelDownstreamHandler {
//
// /**
// * Splits the given buffer in to multiple chunks based on the split
// * threshold.
// */
// public static List<ChannelBuffer> split(ChannelBuffer buffer, int splitThreshold) {
// final int listSize = (int) ((float) buffer.readableBytes() / splitThreshold);
// final ArrayList<ChannelBuffer> fragmentList = new ArrayList<ChannelBuffer>(listSize);
//
// if (buffer.readableBytes() > splitThreshold) {
// int slicePosition = buffer.readerIndex();
// while (slicePosition < buffer.writerIndex()) {
// final int chunkSize = Math.min(splitThreshold, buffer.writerIndex() - slicePosition);
// final ChannelBuffer chunk = buffer.slice(slicePosition, chunkSize);
//
// fragmentList.add(chunk);
// slicePosition += chunkSize;
// }
// }
// else
// fragmentList.add(ChannelBuffers.wrappedBuffer(buffer));
//
// return fragmentList;
// }
//
// private int splitThreshold;
//
// public WriteFragmenter(int splitThreshold) {
// this.splitThreshold = splitThreshold;
// }
//
// public void setSplitThreshold(int splitThreshold) {
// this.splitThreshold = splitThreshold;
// }
//
// @Override
// public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// final ChannelBuffer data = (ChannelBuffer) e.getMessage();
//
// if (data.readableBytes() <= splitThreshold)
// super.writeRequested(ctx, e);
// else {
// final List<ChannelBuffer> fragments = WriteFragmenter.split(data, splitThreshold);
// final ChannelFutureAggregator aggregator = new ChannelFutureAggregator(e.getFuture());
//
// for (ChannelBuffer fragment : fragments) {
// final ChannelFuture fragmentFuture = Channels.future(ctx.getChannel(), true);
// aggregator.addFuture(fragmentFuture);
//
// Channels.write(ctx, fragmentFuture, fragment);
// }
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.Test;
import com.yammer.httptunnel.util.WriteFragmenter; | /*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
public class WriteSplitterTest {
private static final int SPLIT_THRESHOLD = 1024;
@Test
public void testSplit_bufferUnderThreshold() {
ChannelBuffer buffer = createBufferWithContents(800); | // Path: src/main/java/com/yammer/httptunnel/util/WriteFragmenter.java
// public class WriteFragmenter extends SimpleChannelDownstreamHandler {
//
// /**
// * Splits the given buffer in to multiple chunks based on the split
// * threshold.
// */
// public static List<ChannelBuffer> split(ChannelBuffer buffer, int splitThreshold) {
// final int listSize = (int) ((float) buffer.readableBytes() / splitThreshold);
// final ArrayList<ChannelBuffer> fragmentList = new ArrayList<ChannelBuffer>(listSize);
//
// if (buffer.readableBytes() > splitThreshold) {
// int slicePosition = buffer.readerIndex();
// while (slicePosition < buffer.writerIndex()) {
// final int chunkSize = Math.min(splitThreshold, buffer.writerIndex() - slicePosition);
// final ChannelBuffer chunk = buffer.slice(slicePosition, chunkSize);
//
// fragmentList.add(chunk);
// slicePosition += chunkSize;
// }
// }
// else
// fragmentList.add(ChannelBuffers.wrappedBuffer(buffer));
//
// return fragmentList;
// }
//
// private int splitThreshold;
//
// public WriteFragmenter(int splitThreshold) {
// this.splitThreshold = splitThreshold;
// }
//
// public void setSplitThreshold(int splitThreshold) {
// this.splitThreshold = splitThreshold;
// }
//
// @Override
// public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// final ChannelBuffer data = (ChannelBuffer) e.getMessage();
//
// if (data.readableBytes() <= splitThreshold)
// super.writeRequested(ctx, e);
// else {
// final List<ChannelBuffer> fragments = WriteFragmenter.split(data, splitThreshold);
// final ChannelFutureAggregator aggregator = new ChannelFutureAggregator(e.getFuture());
//
// for (ChannelBuffer fragment : fragments) {
// final ChannelFuture fragmentFuture = Channels.future(ctx.getChannel(), true);
// aggregator.addFuture(fragmentFuture);
//
// Channels.write(ctx, fragmentFuture, fragment);
// }
// }
// }
// }
// Path: src/test/java/com/yammer/httptunnel/WriteSplitterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.Test;
import com.yammer.httptunnel.util.WriteFragmenter;
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
public class WriteSplitterTest {
private static final int SPLIT_THRESHOLD = 1024;
@Test
public void testSplit_bufferUnderThreshold() {
ChannelBuffer buffer = createBufferWithContents(800); | List<ChannelBuffer> fragments = WriteFragmenter.split(buffer, |
reines/httptunnel | src/test/java/com/yammer/httptunnel/util/ParameterParserTest.java | // Path: src/main/java/com/yammer/httptunnel/util/ParameterParser.java
// public class ParameterParser {
//
// /** String to be parsed */
// private final char[] chars;
//
// /** Current position in the string */
// private int pos;
//
// /** Default ParameterParser constructor */
// public ParameterParser(String input) {
// if (input == null)
// input = "";
//
// chars = input.toCharArray();
// pos = 0;
// }
//
// /** A helper method to process the parsed token. */
// private String getToken(int start, int end, boolean quoted) {
// // Trim leading white spaces
// while ((start < end) && (Character.isWhitespace(chars[start])))
// start++;
//
// // Trim trailing white spaces
// while ((end > start) && (Character.isWhitespace(chars[end - 1])))
// end--;
//
// // Strip away quotes if necessary
// if (quoted) {
// if (((end - start) >= 2) && (chars[start] == '"') && (chars[end - 1] == '"')) {
// start++;
// end--;
// }
// }
//
// if (end >= start)
// return new String(chars, start, end - start);
//
// return null;
// }
//
// /**
// * Parse out a token until any of the given terminators is encountered.
// */
// private String parseToken(final char[] terminators) {
// int start = pos;
// int end = pos;
//
// while (pos < chars.length) {
// char ch = chars[pos];
// if (StringUtils.inCharArray(terminators, ch))
// break;
//
// end++;
// pos++;
// }
//
// return this.getToken(start, end, false);
// }
//
// /**
// * Parse out a token until any of the given terminators is encountered.
// * Special characters in quoted tokens are escaped.
// */
// private String parseQuotedToken(final char[] terminators) {
// int start = pos;
// int end = pos;
//
// boolean quoted = false;
// boolean charEscaped = false;
//
// while (pos < chars.length) {
// char ch = chars[pos];
// if (!quoted && StringUtils.inCharArray(terminators, ch))
// break;
//
// if (!charEscaped && ch == '"')
// quoted = !quoted;
//
// charEscaped = (!charEscaped && ch == '\\');
// end++;
// pos++;
// }
//
// return this.getToken(start, end, true);
// }
//
// public Map<String, String> split(char separator) {
// final Map<String, String> params = new HashMap<String, String>();
//
// pos = 0;
//
// while (pos < chars.length) {
// final String paramName = this.parseToken(new char[] { '=', separator }).toLowerCase();
// String paramValue = null;
//
// if (pos < chars.length && (chars[pos] == '=')) {
// pos++; // skip '='
// paramValue = this.parseQuotedToken(new char[] { separator });
// }
//
// if (pos < chars.length && (chars[pos] == separator))
// pos++; // skip separator
//
// if (paramName != null && !(paramName.isEmpty() && paramValue == null))
// params.put(paramName, paramValue);
// }
//
// return params;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import org.junit.Test;
import com.yammer.httptunnel.util.ParameterParser; | package com.yammer.httptunnel.util;
public class ParameterParserTest {
@Test
public void testSingleParam() { | // Path: src/main/java/com/yammer/httptunnel/util/ParameterParser.java
// public class ParameterParser {
//
// /** String to be parsed */
// private final char[] chars;
//
// /** Current position in the string */
// private int pos;
//
// /** Default ParameterParser constructor */
// public ParameterParser(String input) {
// if (input == null)
// input = "";
//
// chars = input.toCharArray();
// pos = 0;
// }
//
// /** A helper method to process the parsed token. */
// private String getToken(int start, int end, boolean quoted) {
// // Trim leading white spaces
// while ((start < end) && (Character.isWhitespace(chars[start])))
// start++;
//
// // Trim trailing white spaces
// while ((end > start) && (Character.isWhitespace(chars[end - 1])))
// end--;
//
// // Strip away quotes if necessary
// if (quoted) {
// if (((end - start) >= 2) && (chars[start] == '"') && (chars[end - 1] == '"')) {
// start++;
// end--;
// }
// }
//
// if (end >= start)
// return new String(chars, start, end - start);
//
// return null;
// }
//
// /**
// * Parse out a token until any of the given terminators is encountered.
// */
// private String parseToken(final char[] terminators) {
// int start = pos;
// int end = pos;
//
// while (pos < chars.length) {
// char ch = chars[pos];
// if (StringUtils.inCharArray(terminators, ch))
// break;
//
// end++;
// pos++;
// }
//
// return this.getToken(start, end, false);
// }
//
// /**
// * Parse out a token until any of the given terminators is encountered.
// * Special characters in quoted tokens are escaped.
// */
// private String parseQuotedToken(final char[] terminators) {
// int start = pos;
// int end = pos;
//
// boolean quoted = false;
// boolean charEscaped = false;
//
// while (pos < chars.length) {
// char ch = chars[pos];
// if (!quoted && StringUtils.inCharArray(terminators, ch))
// break;
//
// if (!charEscaped && ch == '"')
// quoted = !quoted;
//
// charEscaped = (!charEscaped && ch == '\\');
// end++;
// pos++;
// }
//
// return this.getToken(start, end, true);
// }
//
// public Map<String, String> split(char separator) {
// final Map<String, String> params = new HashMap<String, String>();
//
// pos = 0;
//
// while (pos < chars.length) {
// final String paramName = this.parseToken(new char[] { '=', separator }).toLowerCase();
// String paramValue = null;
//
// if (pos < chars.length && (chars[pos] == '=')) {
// pos++; // skip '='
// paramValue = this.parseQuotedToken(new char[] { separator });
// }
//
// if (pos < chars.length && (chars[pos] == separator))
// pos++; // skip separator
//
// if (paramName != null && !(paramName.isEmpty() && paramValue == null))
// params.put(paramName, paramValue);
// }
//
// return params;
// }
// }
// Path: src/test/java/com/yammer/httptunnel/util/ParameterParserTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import org.junit.Test;
import com.yammer.httptunnel.util.ParameterParser;
package com.yammer.httptunnel.util;
public class ParameterParserTest {
@Test
public void testSingleParam() { | final ParameterParser parser = new ParameterParser("Realm=\"test\""); |
reines/httptunnel | src/main/java/com/yammer/httptunnel/client/auth/AuthScheme.java | // Path: src/main/java/com/yammer/httptunnel/client/ProxyAuthenticationException.java
// public class ProxyAuthenticationException extends Exception {
//
// private static final long serialVersionUID = 997754190727366945L;
//
// public ProxyAuthenticationException(String message) {
// super(message);
// }
// }
| import java.util.Map;
import org.jboss.netty.handler.codec.http.HttpRequest;
import com.yammer.httptunnel.client.ProxyAuthenticationException; | /*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.client.auth;
/**
* This interface is used by the client end of an http tunnel to handle proxy
* authentication requests.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public interface AuthScheme {
/**
* Gets the name of the authentication method supported by this instance.
*/
public String getName();
/**
* Generates the authentication response header for the given request, using
* the given credentials.
*/ | // Path: src/main/java/com/yammer/httptunnel/client/ProxyAuthenticationException.java
// public class ProxyAuthenticationException extends Exception {
//
// private static final long serialVersionUID = 997754190727366945L;
//
// public ProxyAuthenticationException(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/yammer/httptunnel/client/auth/AuthScheme.java
import java.util.Map;
import org.jboss.netty.handler.codec.http.HttpRequest;
import com.yammer.httptunnel.client.ProxyAuthenticationException;
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.client.auth;
/**
* This interface is used by the client end of an http tunnel to handle proxy
* authentication requests.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public interface AuthScheme {
/**
* Gets the name of the authentication method supported by this instance.
*/
public String getName();
/**
* Generates the authentication response header for the given request, using
* the given credentials.
*/ | public String authenticate(HttpRequest request, Map<String, String> challenge, String username, String password) throws ProxyAuthenticationException; |
reines/httptunnel | src/test/java/com/yammer/httptunnel/client/HttpTunnelClientChannelConfigTest.java | // Path: src/main/java/com/yammer/httptunnel/client/HttpTunnelClientChannelConfig.java
// public class HttpTunnelClientChannelConfig extends HttpTunnelChannelConfig {
// private static final InternalLogger LOG = InternalLoggerFactory.getInstance(HttpTunnelClientChannelConfig.class);
//
// /**
// * The default user-agent used for HTTP tunnel requests.
// */
// public static final String DEFAULT_USER_AGENT = "HttpTunnel";
//
// static final String USER_AGENT_OPTION = "userAgent";
//
// private static final String PROP_PKG = "org.jboss.netty.channel.socket.http.";
//
// private static final String PROP_UserAgent = PROP_PKG + USER_AGENT_OPTION;
//
// private final SocketChannelConfig sendChannelConfig;
// private final SocketChannelConfig pollChannelConfig;
//
// private String userAgent;
//
// HttpTunnelClientChannelConfig(SocketChannelConfig sendChannelConfig, SocketChannelConfig pollChannelConfig) {
// this.sendChannelConfig = sendChannelConfig;
// this.pollChannelConfig = pollChannelConfig;
//
// userAgent = System.getProperty(PROP_UserAgent, DEFAULT_USER_AGENT);
// }
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
//
// /* HTTP TUNNEL SPECIFIC CONFIGURATION */
// // TODO Support all options in the old tunnel (see
// // HttpTunnelingSocketChannelConfig)
// // Mostly SSL, virtual host, and URL prefix
// @Override
// public boolean setOption(String key, Object value) {
// if (USER_AGENT_OPTION.equalsIgnoreCase(key)) {
// this.setUserAgent((String) value);
// return true;
// }
//
// return super.setOption(key, value);
// }
//
// /* GENERIC SOCKET CHANNEL CONFIGURATION */
//
// @Override
// public int getReceiveBufferSize() {
// return pollChannelConfig.getReceiveBufferSize();
// }
//
// @Override
// public void setReceiveBufferSize(int receiveBufferSize) {
// pollChannelConfig.setReceiveBufferSize(receiveBufferSize);
// sendChannelConfig.setReceiveBufferSize(receiveBufferSize);
// }
//
// @Override
// public int getSendBufferSize() {
// return pollChannelConfig.getSendBufferSize();
// }
//
// @Override
// public void setSendBufferSize(int sendBufferSize) {
// pollChannelConfig.setSendBufferSize(sendBufferSize);
// sendChannelConfig.setSendBufferSize(sendBufferSize);
// }
//
// @Override
// public int getSoLinger() {
// return pollChannelConfig.getSoLinger();
// }
//
// @Override
// public void setSoLinger(int soLinger) {
// pollChannelConfig.setSoLinger(soLinger);
// sendChannelConfig.setSoLinger(soLinger);
// }
//
// @Override
// public int getTrafficClass() {
// return pollChannelConfig.getTrafficClass();
// }
//
// @Override
// public void setTrafficClass(int trafficClass) {
// pollChannelConfig.setTrafficClass(1);
// sendChannelConfig.setTrafficClass(1);
// }
//
// @Override
// public boolean isKeepAlive() {
// return pollChannelConfig.isKeepAlive();
// }
//
// @Override
// public void setKeepAlive(boolean keepAlive) {
// pollChannelConfig.setKeepAlive(keepAlive);
// sendChannelConfig.setKeepAlive(keepAlive);
// }
//
// @Override
// public boolean isReuseAddress() {
// return pollChannelConfig.isReuseAddress();
// }
//
// @Override
// public void setReuseAddress(boolean reuseAddress) {
// pollChannelConfig.setReuseAddress(reuseAddress);
// sendChannelConfig.setReuseAddress(reuseAddress);
// }
//
// @Override
// public boolean isTcpNoDelay() {
// return pollChannelConfig.isTcpNoDelay();
// }
//
// @Override
// public void setTcpNoDelay(boolean tcpNoDelay) {
// pollChannelConfig.setTcpNoDelay(true);
// sendChannelConfig.setTcpNoDelay(true);
// }
//
// @Override
// public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
// pollChannelConfig.setPerformancePreferences(connectionTime, latency, bandwidth);
// sendChannelConfig.setPerformancePreferences(connectionTime, latency, bandwidth);
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yammer.httptunnel.client.HttpTunnelClientChannelConfig; | /*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel.client;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
@RunWith(JMock.class)
public class HttpTunnelClientChannelConfigTest {
JUnit4Mockery mockContext = new JUnit4Mockery();
SocketChannelConfig sendChannelConfig;
SocketChannelConfig pollChannelConfig;
| // Path: src/main/java/com/yammer/httptunnel/client/HttpTunnelClientChannelConfig.java
// public class HttpTunnelClientChannelConfig extends HttpTunnelChannelConfig {
// private static final InternalLogger LOG = InternalLoggerFactory.getInstance(HttpTunnelClientChannelConfig.class);
//
// /**
// * The default user-agent used for HTTP tunnel requests.
// */
// public static final String DEFAULT_USER_AGENT = "HttpTunnel";
//
// static final String USER_AGENT_OPTION = "userAgent";
//
// private static final String PROP_PKG = "org.jboss.netty.channel.socket.http.";
//
// private static final String PROP_UserAgent = PROP_PKG + USER_AGENT_OPTION;
//
// private final SocketChannelConfig sendChannelConfig;
// private final SocketChannelConfig pollChannelConfig;
//
// private String userAgent;
//
// HttpTunnelClientChannelConfig(SocketChannelConfig sendChannelConfig, SocketChannelConfig pollChannelConfig) {
// this.sendChannelConfig = sendChannelConfig;
// this.pollChannelConfig = pollChannelConfig;
//
// userAgent = System.getProperty(PROP_UserAgent, DEFAULT_USER_AGENT);
// }
//
// public String getUserAgent() {
// return userAgent;
// }
//
// public void setUserAgent(String userAgent) {
// this.userAgent = userAgent;
// }
//
// /* HTTP TUNNEL SPECIFIC CONFIGURATION */
// // TODO Support all options in the old tunnel (see
// // HttpTunnelingSocketChannelConfig)
// // Mostly SSL, virtual host, and URL prefix
// @Override
// public boolean setOption(String key, Object value) {
// if (USER_AGENT_OPTION.equalsIgnoreCase(key)) {
// this.setUserAgent((String) value);
// return true;
// }
//
// return super.setOption(key, value);
// }
//
// /* GENERIC SOCKET CHANNEL CONFIGURATION */
//
// @Override
// public int getReceiveBufferSize() {
// return pollChannelConfig.getReceiveBufferSize();
// }
//
// @Override
// public void setReceiveBufferSize(int receiveBufferSize) {
// pollChannelConfig.setReceiveBufferSize(receiveBufferSize);
// sendChannelConfig.setReceiveBufferSize(receiveBufferSize);
// }
//
// @Override
// public int getSendBufferSize() {
// return pollChannelConfig.getSendBufferSize();
// }
//
// @Override
// public void setSendBufferSize(int sendBufferSize) {
// pollChannelConfig.setSendBufferSize(sendBufferSize);
// sendChannelConfig.setSendBufferSize(sendBufferSize);
// }
//
// @Override
// public int getSoLinger() {
// return pollChannelConfig.getSoLinger();
// }
//
// @Override
// public void setSoLinger(int soLinger) {
// pollChannelConfig.setSoLinger(soLinger);
// sendChannelConfig.setSoLinger(soLinger);
// }
//
// @Override
// public int getTrafficClass() {
// return pollChannelConfig.getTrafficClass();
// }
//
// @Override
// public void setTrafficClass(int trafficClass) {
// pollChannelConfig.setTrafficClass(1);
// sendChannelConfig.setTrafficClass(1);
// }
//
// @Override
// public boolean isKeepAlive() {
// return pollChannelConfig.isKeepAlive();
// }
//
// @Override
// public void setKeepAlive(boolean keepAlive) {
// pollChannelConfig.setKeepAlive(keepAlive);
// sendChannelConfig.setKeepAlive(keepAlive);
// }
//
// @Override
// public boolean isReuseAddress() {
// return pollChannelConfig.isReuseAddress();
// }
//
// @Override
// public void setReuseAddress(boolean reuseAddress) {
// pollChannelConfig.setReuseAddress(reuseAddress);
// sendChannelConfig.setReuseAddress(reuseAddress);
// }
//
// @Override
// public boolean isTcpNoDelay() {
// return pollChannelConfig.isTcpNoDelay();
// }
//
// @Override
// public void setTcpNoDelay(boolean tcpNoDelay) {
// pollChannelConfig.setTcpNoDelay(true);
// sendChannelConfig.setTcpNoDelay(true);
// }
//
// @Override
// public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
// pollChannelConfig.setPerformancePreferences(connectionTime, latency, bandwidth);
// sendChannelConfig.setPerformancePreferences(connectionTime, latency, bandwidth);
// }
// }
// Path: src/test/java/com/yammer/httptunnel/client/HttpTunnelClientChannelConfigTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yammer.httptunnel.client.HttpTunnelClientChannelConfig;
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel.client;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
@RunWith(JMock.class)
public class HttpTunnelClientChannelConfigTest {
JUnit4Mockery mockContext = new JUnit4Mockery();
SocketChannelConfig sendChannelConfig;
SocketChannelConfig pollChannelConfig;
| HttpTunnelClientChannelConfig config; |
reines/httptunnel | src/test/java/com/yammer/httptunnel/util/NettyTestUtils.java | // Path: src/main/java/com/yammer/httptunnel/client/HttpTunnelClientChannelFactory.java
// public class HttpTunnelClientChannelFactory implements ClientSocketChannelFactory {
//
// private final ClientSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelClientChannelFactory(ClientSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelClientChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelClientChannel(this, pipeline, new HttpTunnelClientChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactory.java
// public class HttpTunnelServerChannelFactory implements ServerSocketChannelFactory {
//
// private final ServerSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelServerChannelFactory(ServerSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelServerChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelServerChannel(this, pipeline, new HttpTunnelServerChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
| import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelState;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DownstreamMessageEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.UpstreamMessageEvent;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import com.yammer.httptunnel.client.HttpTunnelClientChannelFactory;
import com.yammer.httptunnel.server.HttpTunnelServerChannelFactory; | return new InetSocketAddress(InetAddress.getByAddress(addr), port);
}
catch (UnknownHostException e) {
throw new RuntimeException("Bad address in test");
}
}
public static Throwable checkIsExceptionEvent(ChannelEvent ev) {
assertTrue(ev instanceof ExceptionEvent);
ExceptionEvent exceptionEv = (ExceptionEvent) ev;
return exceptionEv.getCause();
}
public static ChannelStateEvent checkIsStateEvent(ChannelEvent event, ChannelState expectedState, Object expectedValue) {
assertTrue(event instanceof ChannelStateEvent);
ChannelStateEvent stateEvent = (ChannelStateEvent) event;
Assert.assertEquals(expectedState, stateEvent.getState());
Assert.assertEquals(expectedValue, stateEvent.getValue());
return stateEvent;
}
public static InetAddress getLocalHost() throws UnknownHostException {
return InetAddress.getLocalHost();
}
public static Channel createServerChannel(InetSocketAddress addr, ChannelPipelineFactory pipelineFactory) {
// TCP socket factory
ServerSocketChannelFactory socketFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
// HTTP socket factory | // Path: src/main/java/com/yammer/httptunnel/client/HttpTunnelClientChannelFactory.java
// public class HttpTunnelClientChannelFactory implements ClientSocketChannelFactory {
//
// private final ClientSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelClientChannelFactory(ClientSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelClientChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelClientChannel(this, pipeline, new HttpTunnelClientChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactory.java
// public class HttpTunnelServerChannelFactory implements ServerSocketChannelFactory {
//
// private final ServerSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelServerChannelFactory(ServerSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelServerChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelServerChannel(this, pipeline, new HttpTunnelServerChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
// Path: src/test/java/com/yammer/httptunnel/util/NettyTestUtils.java
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelState;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DownstreamMessageEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.UpstreamMessageEvent;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import com.yammer.httptunnel.client.HttpTunnelClientChannelFactory;
import com.yammer.httptunnel.server.HttpTunnelServerChannelFactory;
return new InetSocketAddress(InetAddress.getByAddress(addr), port);
}
catch (UnknownHostException e) {
throw new RuntimeException("Bad address in test");
}
}
public static Throwable checkIsExceptionEvent(ChannelEvent ev) {
assertTrue(ev instanceof ExceptionEvent);
ExceptionEvent exceptionEv = (ExceptionEvent) ev;
return exceptionEv.getCause();
}
public static ChannelStateEvent checkIsStateEvent(ChannelEvent event, ChannelState expectedState, Object expectedValue) {
assertTrue(event instanceof ChannelStateEvent);
ChannelStateEvent stateEvent = (ChannelStateEvent) event;
Assert.assertEquals(expectedState, stateEvent.getState());
Assert.assertEquals(expectedValue, stateEvent.getValue());
return stateEvent;
}
public static InetAddress getLocalHost() throws UnknownHostException {
return InetAddress.getLocalHost();
}
public static Channel createServerChannel(InetSocketAddress addr, ChannelPipelineFactory pipelineFactory) {
// TCP socket factory
ServerSocketChannelFactory socketFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
// HTTP socket factory | socketFactory = new HttpTunnelServerChannelFactory(socketFactory); |
reines/httptunnel | src/test/java/com/yammer/httptunnel/util/NettyTestUtils.java | // Path: src/main/java/com/yammer/httptunnel/client/HttpTunnelClientChannelFactory.java
// public class HttpTunnelClientChannelFactory implements ClientSocketChannelFactory {
//
// private final ClientSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelClientChannelFactory(ClientSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelClientChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelClientChannel(this, pipeline, new HttpTunnelClientChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactory.java
// public class HttpTunnelServerChannelFactory implements ServerSocketChannelFactory {
//
// private final ServerSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelServerChannelFactory(ServerSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelServerChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelServerChannel(this, pipeline, new HttpTunnelServerChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
| import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelState;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DownstreamMessageEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.UpstreamMessageEvent;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import com.yammer.httptunnel.client.HttpTunnelClientChannelFactory;
import com.yammer.httptunnel.server.HttpTunnelServerChannelFactory; | Assert.assertEquals(expectedState, stateEvent.getState());
Assert.assertEquals(expectedValue, stateEvent.getValue());
return stateEvent;
}
public static InetAddress getLocalHost() throws UnknownHostException {
return InetAddress.getLocalHost();
}
public static Channel createServerChannel(InetSocketAddress addr, ChannelPipelineFactory pipelineFactory) {
// TCP socket factory
ServerSocketChannelFactory socketFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
// HTTP socket factory
socketFactory = new HttpTunnelServerChannelFactory(socketFactory);
final ServerBootstrap bootstrap = new ServerBootstrap(socketFactory);
bootstrap.setPipelineFactory(pipelineFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("reuseAddress", true);
return bootstrap.bind(addr);
}
public static Channel createClientChannel(InetSocketAddress addr, ChannelPipelineFactory pipelineFactory, int timeout) {
// TCP socket factory
ClientSocketChannelFactory socketFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
// HTTP socket factory | // Path: src/main/java/com/yammer/httptunnel/client/HttpTunnelClientChannelFactory.java
// public class HttpTunnelClientChannelFactory implements ClientSocketChannelFactory {
//
// private final ClientSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelClientChannelFactory(ClientSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelClientChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelClientChannel(this, pipeline, new HttpTunnelClientChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactory.java
// public class HttpTunnelServerChannelFactory implements ServerSocketChannelFactory {
//
// private final ServerSocketChannelFactory factory;
// private final ChannelGroup realConnections;
//
// public HttpTunnelServerChannelFactory(ServerSocketChannelFactory factory) {
// this.factory = factory;
//
// realConnections = new DefaultChannelGroup();
// }
//
// @Override
// public HttpTunnelServerChannel newChannel(ChannelPipeline pipeline) {
// return new HttpTunnelServerChannel(this, pipeline, new HttpTunnelServerChannelSink(), factory, realConnections);
// }
//
// @Override
// public void releaseExternalResources() {
// factory.releaseExternalResources();
// }
// }
// Path: src/test/java/com/yammer/httptunnel/util/NettyTestUtils.java
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelState;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DownstreamMessageEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.UpstreamMessageEvent;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import com.yammer.httptunnel.client.HttpTunnelClientChannelFactory;
import com.yammer.httptunnel.server.HttpTunnelServerChannelFactory;
Assert.assertEquals(expectedState, stateEvent.getState());
Assert.assertEquals(expectedValue, stateEvent.getValue());
return stateEvent;
}
public static InetAddress getLocalHost() throws UnknownHostException {
return InetAddress.getLocalHost();
}
public static Channel createServerChannel(InetSocketAddress addr, ChannelPipelineFactory pipelineFactory) {
// TCP socket factory
ServerSocketChannelFactory socketFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
// HTTP socket factory
socketFactory = new HttpTunnelServerChannelFactory(socketFactory);
final ServerBootstrap bootstrap = new ServerBootstrap(socketFactory);
bootstrap.setPipelineFactory(pipelineFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("reuseAddress", true);
return bootstrap.bind(addr);
}
public static Channel createClientChannel(InetSocketAddress addr, ChannelPipelineFactory pipelineFactory, int timeout) {
// TCP socket factory
ClientSocketChannelFactory socketFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
// HTTP socket factory | socketFactory = new HttpTunnelClientChannelFactory(socketFactory); |
reines/httptunnel | src/test/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactoryTest.java | // Path: src/test/java/com/yammer/httptunnel/FakeChannelSink.java
// public class FakeChannelSink extends AbstractChannelSink {
//
// public final Queue<ChannelEvent> events;
//
// public FakeChannelSink() {
// events = new LinkedList<ChannelEvent>();
// }
//
// @Override
// public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
// events.add(e);
// }
// }
//
// Path: src/test/java/com/yammer/httptunnel/FakeServerSocketChannel.java
// public class FakeServerSocketChannel extends AbstractChannel implements
// ServerSocketChannel {
//
// public boolean bound;
//
// public boolean connected;
//
// public InetSocketAddress remoteAddress;
//
// public InetSocketAddress localAddress;
//
// public ServerSocketChannelConfig config = new FakeServerSocketChannelConfig();
//
// public FakeServerSocketChannel(ChannelFactory factory,
// ChannelPipeline pipeline, ChannelSink sink) {
// super(null, factory, pipeline, sink);
// }
//
// @Override
// public ServerSocketChannelConfig getConfig() {
// return config;
// }
//
// @Override
// public InetSocketAddress getLocalAddress() {
// return localAddress;
// }
//
// @Override
// public InetSocketAddress getRemoteAddress() {
// return remoteAddress;
// }
//
// @Override
// public boolean isBound() {
// return bound;
// }
//
// @Override
// public boolean isConnected() {
// return connected;
// }
//
// public FakeSocketChannel acceptNewConnection(
// InetSocketAddress remoteAddress, ChannelSink sink) throws Exception {
// ChannelPipeline newPipeline = getConfig().getPipelineFactory()
// .getPipeline();
// FakeSocketChannel newChannel = new FakeSocketChannel(this,
// getFactory(), newPipeline, sink);
// newChannel.localAddress = localAddress;
// newChannel.remoteAddress = remoteAddress;
// fireChannelOpen(newChannel);
// fireChannelBound(newChannel, newChannel.localAddress);
// fireChannelConnected(this, newChannel.remoteAddress);
//
// return newChannel;
// }
//
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import com.yammer.httptunnel.FakeChannelSink;
import com.yammer.httptunnel.FakeServerSocketChannel;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before; | /*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel.server;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
@RunWith(JMock.class)
public class HttpTunnelServerChannelFactoryTest {
private final JUnit4Mockery mockContext = new JUnit4Mockery();
ServerSocketChannelFactory realChannelFactory;
private HttpTunnelServerChannelFactory factory;
ServerSocketChannel realChannel;
@Before
public void setUp() throws Exception {
realChannelFactory = mockContext.mock(ServerSocketChannelFactory.class);
factory = new HttpTunnelServerChannelFactory(realChannelFactory);
ChannelPipeline pipeline = Channels.pipeline(new SimpleChannelHandler()); | // Path: src/test/java/com/yammer/httptunnel/FakeChannelSink.java
// public class FakeChannelSink extends AbstractChannelSink {
//
// public final Queue<ChannelEvent> events;
//
// public FakeChannelSink() {
// events = new LinkedList<ChannelEvent>();
// }
//
// @Override
// public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
// events.add(e);
// }
// }
//
// Path: src/test/java/com/yammer/httptunnel/FakeServerSocketChannel.java
// public class FakeServerSocketChannel extends AbstractChannel implements
// ServerSocketChannel {
//
// public boolean bound;
//
// public boolean connected;
//
// public InetSocketAddress remoteAddress;
//
// public InetSocketAddress localAddress;
//
// public ServerSocketChannelConfig config = new FakeServerSocketChannelConfig();
//
// public FakeServerSocketChannel(ChannelFactory factory,
// ChannelPipeline pipeline, ChannelSink sink) {
// super(null, factory, pipeline, sink);
// }
//
// @Override
// public ServerSocketChannelConfig getConfig() {
// return config;
// }
//
// @Override
// public InetSocketAddress getLocalAddress() {
// return localAddress;
// }
//
// @Override
// public InetSocketAddress getRemoteAddress() {
// return remoteAddress;
// }
//
// @Override
// public boolean isBound() {
// return bound;
// }
//
// @Override
// public boolean isConnected() {
// return connected;
// }
//
// public FakeSocketChannel acceptNewConnection(
// InetSocketAddress remoteAddress, ChannelSink sink) throws Exception {
// ChannelPipeline newPipeline = getConfig().getPipelineFactory()
// .getPipeline();
// FakeSocketChannel newChannel = new FakeSocketChannel(this,
// getFactory(), newPipeline, sink);
// newChannel.localAddress = localAddress;
// newChannel.remoteAddress = remoteAddress;
// fireChannelOpen(newChannel);
// fireChannelBound(newChannel, newChannel.localAddress);
// fireChannelConnected(this, newChannel.remoteAddress);
//
// return newChannel;
// }
//
// }
// Path: src/test/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactoryTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yammer.httptunnel.FakeChannelSink;
import com.yammer.httptunnel.FakeServerSocketChannel;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel.server;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
@RunWith(JMock.class)
public class HttpTunnelServerChannelFactoryTest {
private final JUnit4Mockery mockContext = new JUnit4Mockery();
ServerSocketChannelFactory realChannelFactory;
private HttpTunnelServerChannelFactory factory;
ServerSocketChannel realChannel;
@Before
public void setUp() throws Exception {
realChannelFactory = mockContext.mock(ServerSocketChannelFactory.class);
factory = new HttpTunnelServerChannelFactory(realChannelFactory);
ChannelPipeline pipeline = Channels.pipeline(new SimpleChannelHandler()); | realChannel = new FakeServerSocketChannel(factory, pipeline, |
reines/httptunnel | src/test/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactoryTest.java | // Path: src/test/java/com/yammer/httptunnel/FakeChannelSink.java
// public class FakeChannelSink extends AbstractChannelSink {
//
// public final Queue<ChannelEvent> events;
//
// public FakeChannelSink() {
// events = new LinkedList<ChannelEvent>();
// }
//
// @Override
// public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
// events.add(e);
// }
// }
//
// Path: src/test/java/com/yammer/httptunnel/FakeServerSocketChannel.java
// public class FakeServerSocketChannel extends AbstractChannel implements
// ServerSocketChannel {
//
// public boolean bound;
//
// public boolean connected;
//
// public InetSocketAddress remoteAddress;
//
// public InetSocketAddress localAddress;
//
// public ServerSocketChannelConfig config = new FakeServerSocketChannelConfig();
//
// public FakeServerSocketChannel(ChannelFactory factory,
// ChannelPipeline pipeline, ChannelSink sink) {
// super(null, factory, pipeline, sink);
// }
//
// @Override
// public ServerSocketChannelConfig getConfig() {
// return config;
// }
//
// @Override
// public InetSocketAddress getLocalAddress() {
// return localAddress;
// }
//
// @Override
// public InetSocketAddress getRemoteAddress() {
// return remoteAddress;
// }
//
// @Override
// public boolean isBound() {
// return bound;
// }
//
// @Override
// public boolean isConnected() {
// return connected;
// }
//
// public FakeSocketChannel acceptNewConnection(
// InetSocketAddress remoteAddress, ChannelSink sink) throws Exception {
// ChannelPipeline newPipeline = getConfig().getPipelineFactory()
// .getPipeline();
// FakeSocketChannel newChannel = new FakeSocketChannel(this,
// getFactory(), newPipeline, sink);
// newChannel.localAddress = localAddress;
// newChannel.remoteAddress = remoteAddress;
// fireChannelOpen(newChannel);
// fireChannelBound(newChannel, newChannel.localAddress);
// fireChannelConnected(this, newChannel.remoteAddress);
//
// return newChannel;
// }
//
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import com.yammer.httptunnel.FakeChannelSink;
import com.yammer.httptunnel.FakeServerSocketChannel;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before; | /*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel.server;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
@RunWith(JMock.class)
public class HttpTunnelServerChannelFactoryTest {
private final JUnit4Mockery mockContext = new JUnit4Mockery();
ServerSocketChannelFactory realChannelFactory;
private HttpTunnelServerChannelFactory factory;
ServerSocketChannel realChannel;
@Before
public void setUp() throws Exception {
realChannelFactory = mockContext.mock(ServerSocketChannelFactory.class);
factory = new HttpTunnelServerChannelFactory(realChannelFactory);
ChannelPipeline pipeline = Channels.pipeline(new SimpleChannelHandler());
realChannel = new FakeServerSocketChannel(factory, pipeline, | // Path: src/test/java/com/yammer/httptunnel/FakeChannelSink.java
// public class FakeChannelSink extends AbstractChannelSink {
//
// public final Queue<ChannelEvent> events;
//
// public FakeChannelSink() {
// events = new LinkedList<ChannelEvent>();
// }
//
// @Override
// public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
// events.add(e);
// }
// }
//
// Path: src/test/java/com/yammer/httptunnel/FakeServerSocketChannel.java
// public class FakeServerSocketChannel extends AbstractChannel implements
// ServerSocketChannel {
//
// public boolean bound;
//
// public boolean connected;
//
// public InetSocketAddress remoteAddress;
//
// public InetSocketAddress localAddress;
//
// public ServerSocketChannelConfig config = new FakeServerSocketChannelConfig();
//
// public FakeServerSocketChannel(ChannelFactory factory,
// ChannelPipeline pipeline, ChannelSink sink) {
// super(null, factory, pipeline, sink);
// }
//
// @Override
// public ServerSocketChannelConfig getConfig() {
// return config;
// }
//
// @Override
// public InetSocketAddress getLocalAddress() {
// return localAddress;
// }
//
// @Override
// public InetSocketAddress getRemoteAddress() {
// return remoteAddress;
// }
//
// @Override
// public boolean isBound() {
// return bound;
// }
//
// @Override
// public boolean isConnected() {
// return connected;
// }
//
// public FakeSocketChannel acceptNewConnection(
// InetSocketAddress remoteAddress, ChannelSink sink) throws Exception {
// ChannelPipeline newPipeline = getConfig().getPipelineFactory()
// .getPipeline();
// FakeSocketChannel newChannel = new FakeSocketChannel(this,
// getFactory(), newPipeline, sink);
// newChannel.localAddress = localAddress;
// newChannel.remoteAddress = remoteAddress;
// fireChannelOpen(newChannel);
// fireChannelBound(newChannel, newChannel.localAddress);
// fireChannelConnected(this, newChannel.remoteAddress);
//
// return newChannel;
// }
//
// }
// Path: src/test/java/com/yammer/httptunnel/server/HttpTunnelServerChannelFactoryTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yammer.httptunnel.FakeChannelSink;
import com.yammer.httptunnel.FakeServerSocketChannel;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
/*
* Copyright 2009 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.yammer.httptunnel.server;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
*/
@RunWith(JMock.class)
public class HttpTunnelServerChannelFactoryTest {
private final JUnit4Mockery mockContext = new JUnit4Mockery();
ServerSocketChannelFactory realChannelFactory;
private HttpTunnelServerChannelFactory factory;
ServerSocketChannel realChannel;
@Before
public void setUp() throws Exception {
realChannelFactory = mockContext.mock(ServerSocketChannelFactory.class);
factory = new HttpTunnelServerChannelFactory(realChannelFactory);
ChannelPipeline pipeline = Channels.pipeline(new SimpleChannelHandler());
realChannel = new FakeServerSocketChannel(factory, pipeline, | new FakeChannelSink()); |
reines/httptunnel | src/test/java/com/yammer/httptunnel/util/StringUtilsTest.java | // Path: src/main/java/com/yammer/httptunnel/util/StringUtils.java
// public class StringUtils {
//
// private StringUtils() { }
//
// public static String capitalize(String str) {
// if (str.isEmpty())
// return str;
//
// return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
// }
//
// public static String leftPad(String str, int length, char padding) {
// final int paddingLength = length - str.length();
// if (paddingLength < 0)
// return str;
//
// final StringBuilder builder = new StringBuilder(length);
//
// while (builder.length() < paddingLength)
// builder.append(padding);
//
// builder.append(str);
//
// return builder.toString();
// }
//
// public static boolean inCharArray(char[] haystack, char needle) {
// for (char candidate : haystack) {
// if (candidate == needle)
// return true;
// }
//
// return false;
// }
//
// public static boolean inStringArray(String[] haystack, String needle) {
// for (String candidate : haystack) {
// if (candidate == null) {
// if (needle == null)
// return true;
//
// continue;
// }
//
// if (candidate.equals(needle))
// return true;
// }
//
// return false;
// }
//
// public static String bytesToHex(byte[] bytes) {
// final Formatter formatter = new Formatter();
//
// for (byte b : bytes)
// formatter.format("%02x", b);
//
// return formatter.toString();
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.yammer.httptunnel.util.StringUtils; | package com.yammer.httptunnel.util;
public class StringUtilsTest {
@Test
public void testCapitalize() { | // Path: src/main/java/com/yammer/httptunnel/util/StringUtils.java
// public class StringUtils {
//
// private StringUtils() { }
//
// public static String capitalize(String str) {
// if (str.isEmpty())
// return str;
//
// return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
// }
//
// public static String leftPad(String str, int length, char padding) {
// final int paddingLength = length - str.length();
// if (paddingLength < 0)
// return str;
//
// final StringBuilder builder = new StringBuilder(length);
//
// while (builder.length() < paddingLength)
// builder.append(padding);
//
// builder.append(str);
//
// return builder.toString();
// }
//
// public static boolean inCharArray(char[] haystack, char needle) {
// for (char candidate : haystack) {
// if (candidate == needle)
// return true;
// }
//
// return false;
// }
//
// public static boolean inStringArray(String[] haystack, String needle) {
// for (String candidate : haystack) {
// if (candidate == null) {
// if (needle == null)
// return true;
//
// continue;
// }
//
// if (candidate.equals(needle))
// return true;
// }
//
// return false;
// }
//
// public static String bytesToHex(byte[] bytes) {
// final Formatter formatter = new Formatter();
//
// for (byte b : bytes)
// formatter.format("%02x", b);
//
// return formatter.toString();
// }
// }
// Path: src/test/java/com/yammer/httptunnel/util/StringUtilsTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.yammer.httptunnel.util.StringUtils;
package com.yammer.httptunnel.util;
public class StringUtilsTest {
@Test
public void testCapitalize() { | assertEquals("Hello world", StringUtils.capitalize("hello world")); |
reines/httptunnel | src/main/java/com/yammer/httptunnel/client/auth/DigestAuthScheme.java | // Path: src/main/java/com/yammer/httptunnel/client/ProxyAuthenticationException.java
// public class ProxyAuthenticationException extends Exception {
//
// private static final long serialVersionUID = 997754190727366945L;
//
// public ProxyAuthenticationException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/StringUtils.java
// public class StringUtils {
//
// private StringUtils() { }
//
// public static String capitalize(String str) {
// if (str.isEmpty())
// return str;
//
// return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
// }
//
// public static String leftPad(String str, int length, char padding) {
// final int paddingLength = length - str.length();
// if (paddingLength < 0)
// return str;
//
// final StringBuilder builder = new StringBuilder(length);
//
// while (builder.length() < paddingLength)
// builder.append(padding);
//
// builder.append(str);
//
// return builder.toString();
// }
//
// public static boolean inCharArray(char[] haystack, char needle) {
// for (char candidate : haystack) {
// if (candidate == needle)
// return true;
// }
//
// return false;
// }
//
// public static boolean inStringArray(String[] haystack, String needle) {
// for (String candidate : haystack) {
// if (candidate == null) {
// if (needle == null)
// return true;
//
// continue;
// }
//
// if (candidate.equals(needle))
// return true;
// }
//
// return false;
// }
//
// public static String bytesToHex(byte[] bytes) {
// final Formatter formatter = new Formatter();
//
// for (byte b : bytes)
// formatter.format("%02x", b);
//
// return formatter.toString();
// }
// }
| import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.jboss.netty.handler.codec.http.HttpRequest;
import com.yammer.httptunnel.client.ProxyAuthenticationException;
import com.yammer.httptunnel.util.StringUtils; | /*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.client.auth;
/**
* An implementation of HTTP digest authentication for use with proxy
* authentication. See RFC 2617.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public class DigestAuthScheme implements AuthScheme {
private static final String NAME = "digest";
private static final String[] requiredParams = {"realm", "nonce", "qop"}; // Technically qop is optional, but *should* be implemented
private static final Random random;
static {
random = new Random();
}
private static String generateNonce() {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
| // Path: src/main/java/com/yammer/httptunnel/client/ProxyAuthenticationException.java
// public class ProxyAuthenticationException extends Exception {
//
// private static final long serialVersionUID = 997754190727366945L;
//
// public ProxyAuthenticationException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/StringUtils.java
// public class StringUtils {
//
// private StringUtils() { }
//
// public static String capitalize(String str) {
// if (str.isEmpty())
// return str;
//
// return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
// }
//
// public static String leftPad(String str, int length, char padding) {
// final int paddingLength = length - str.length();
// if (paddingLength < 0)
// return str;
//
// final StringBuilder builder = new StringBuilder(length);
//
// while (builder.length() < paddingLength)
// builder.append(padding);
//
// builder.append(str);
//
// return builder.toString();
// }
//
// public static boolean inCharArray(char[] haystack, char needle) {
// for (char candidate : haystack) {
// if (candidate == needle)
// return true;
// }
//
// return false;
// }
//
// public static boolean inStringArray(String[] haystack, String needle) {
// for (String candidate : haystack) {
// if (candidate == null) {
// if (needle == null)
// return true;
//
// continue;
// }
//
// if (candidate.equals(needle))
// return true;
// }
//
// return false;
// }
//
// public static String bytesToHex(byte[] bytes) {
// final Formatter formatter = new Formatter();
//
// for (byte b : bytes)
// formatter.format("%02x", b);
//
// return formatter.toString();
// }
// }
// Path: src/main/java/com/yammer/httptunnel/client/auth/DigestAuthScheme.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.jboss.netty.handler.codec.http.HttpRequest;
import com.yammer.httptunnel.client.ProxyAuthenticationException;
import com.yammer.httptunnel.util.StringUtils;
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.client.auth;
/**
* An implementation of HTTP digest authentication for use with proxy
* authentication. See RFC 2617.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public class DigestAuthScheme implements AuthScheme {
private static final String NAME = "digest";
private static final String[] requiredParams = {"realm", "nonce", "qop"}; // Technically qop is optional, but *should* be implemented
private static final Random random;
static {
random = new Random();
}
private static String generateNonce() {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
| return StringUtils.bytesToHex(bytes); |
reines/httptunnel | src/main/java/com/yammer/httptunnel/client/auth/DigestAuthScheme.java | // Path: src/main/java/com/yammer/httptunnel/client/ProxyAuthenticationException.java
// public class ProxyAuthenticationException extends Exception {
//
// private static final long serialVersionUID = 997754190727366945L;
//
// public ProxyAuthenticationException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/StringUtils.java
// public class StringUtils {
//
// private StringUtils() { }
//
// public static String capitalize(String str) {
// if (str.isEmpty())
// return str;
//
// return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
// }
//
// public static String leftPad(String str, int length, char padding) {
// final int paddingLength = length - str.length();
// if (paddingLength < 0)
// return str;
//
// final StringBuilder builder = new StringBuilder(length);
//
// while (builder.length() < paddingLength)
// builder.append(padding);
//
// builder.append(str);
//
// return builder.toString();
// }
//
// public static boolean inCharArray(char[] haystack, char needle) {
// for (char candidate : haystack) {
// if (candidate == needle)
// return true;
// }
//
// return false;
// }
//
// public static boolean inStringArray(String[] haystack, String needle) {
// for (String candidate : haystack) {
// if (candidate == null) {
// if (needle == null)
// return true;
//
// continue;
// }
//
// if (candidate.equals(needle))
// return true;
// }
//
// return false;
// }
//
// public static String bytesToHex(byte[] bytes) {
// final Formatter formatter = new Formatter();
//
// for (byte b : bytes)
// formatter.format("%02x", b);
//
// return formatter.toString();
// }
// }
| import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.jboss.netty.handler.codec.http.HttpRequest;
import com.yammer.httptunnel.client.ProxyAuthenticationException;
import com.yammer.httptunnel.util.StringUtils; | }
private static String generateHA2(String method, String uri) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(String.format("%s:%s", method, uri).getBytes());
return StringUtils.bytesToHex(digest.digest());
}
private static String generateResult(String HA1, String nonce, String nc, String cnonce, String qop, String HA2) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(String.format("%s:%s:%s:%s:%s:%s", HA1, nonce, nc, cnonce, qop, HA2).getBytes());
return StringUtils.bytesToHex(digest.digest());
}
private String cnonce;
private int counter;
public DigestAuthScheme() {
cnonce = DigestAuthScheme.generateNonce();
counter = 0;
}
@Override
public String getName() {
return NAME;
}
@Override | // Path: src/main/java/com/yammer/httptunnel/client/ProxyAuthenticationException.java
// public class ProxyAuthenticationException extends Exception {
//
// private static final long serialVersionUID = 997754190727366945L;
//
// public ProxyAuthenticationException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/StringUtils.java
// public class StringUtils {
//
// private StringUtils() { }
//
// public static String capitalize(String str) {
// if (str.isEmpty())
// return str;
//
// return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
// }
//
// public static String leftPad(String str, int length, char padding) {
// final int paddingLength = length - str.length();
// if (paddingLength < 0)
// return str;
//
// final StringBuilder builder = new StringBuilder(length);
//
// while (builder.length() < paddingLength)
// builder.append(padding);
//
// builder.append(str);
//
// return builder.toString();
// }
//
// public static boolean inCharArray(char[] haystack, char needle) {
// for (char candidate : haystack) {
// if (candidate == needle)
// return true;
// }
//
// return false;
// }
//
// public static boolean inStringArray(String[] haystack, String needle) {
// for (String candidate : haystack) {
// if (candidate == null) {
// if (needle == null)
// return true;
//
// continue;
// }
//
// if (candidate.equals(needle))
// return true;
// }
//
// return false;
// }
//
// public static String bytesToHex(byte[] bytes) {
// final Formatter formatter = new Formatter();
//
// for (byte b : bytes)
// formatter.format("%02x", b);
//
// return formatter.toString();
// }
// }
// Path: src/main/java/com/yammer/httptunnel/client/auth/DigestAuthScheme.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.jboss.netty.handler.codec.http.HttpRequest;
import com.yammer.httptunnel.client.ProxyAuthenticationException;
import com.yammer.httptunnel.util.StringUtils;
}
private static String generateHA2(String method, String uri) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(String.format("%s:%s", method, uri).getBytes());
return StringUtils.bytesToHex(digest.digest());
}
private static String generateResult(String HA1, String nonce, String nc, String cnonce, String qop, String HA2) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(String.format("%s:%s:%s:%s:%s:%s", HA1, nonce, nc, cnonce, qop, HA2).getBytes());
return StringUtils.bytesToHex(digest.digest());
}
private String cnonce;
private int counter;
public DigestAuthScheme() {
cnonce = DigestAuthScheme.generateNonce();
counter = 0;
}
@Override
public String getName() {
return NAME;
}
@Override | public String authenticate(HttpRequest request, Map<String, String> challenge, String username, String password) throws ProxyAuthenticationException { |
reines/httptunnel | src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannel.java | // Path: src/main/java/com/yammer/httptunnel/state/BindState.java
// public enum BindState {
// /**
// * The channel is currently not bound to any address.
// */
// UNBOUND,
//
// /**
// * The channel is currently in the process of binding to a local address.
// */
// BINDING,
//
// /**
// * The channel is currently bound to a local address.
// */
// BOUND,
//
// /**
// * The channel is currently in the process of unbinding from a local
// * address.
// */
// UNBINDING;
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
| import java.net.InetSocketAddress;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.netty.channel.AbstractServerChannel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineException;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import com.yammer.httptunnel.state.BindState;
import com.yammer.httptunnel.util.TunnelIdGenerator; | /*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.server;
/**
* The server end of an HTTP tunnel, created by an
* {@link HttpTunnelServerChannelFactory}. Channels of this type are designed to
* emulate a normal TCP based server socket channel as far as is feasible within
* the limitations of the HTTP 1.0 protocol, and the usage patterns permitted by
* commonly used HTTP proxies and firewalls.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public class HttpTunnelServerChannel extends AbstractServerChannel implements ServerSocketChannel {
private static final InternalLogger LOG = InternalLoggerFactory.getInstance(HttpTunnelServerChannel.class);
private static final Random random;
static {
random = new Random();
}
private final String tunnelIdPrefix;
private final ConcurrentHashMap<String, HttpTunnelAcceptedChannel> tunnels;
private final ServerSocketChannel realChannel;
private final HttpTunnelServerChannelConfig config;
private final AtomicBoolean opened; | // Path: src/main/java/com/yammer/httptunnel/state/BindState.java
// public enum BindState {
// /**
// * The channel is currently not bound to any address.
// */
// UNBOUND,
//
// /**
// * The channel is currently in the process of binding to a local address.
// */
// BINDING,
//
// /**
// * The channel is currently bound to a local address.
// */
// BOUND,
//
// /**
// * The channel is currently in the process of unbinding from a local
// * address.
// */
// UNBINDING;
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannel.java
import java.net.InetSocketAddress;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.netty.channel.AbstractServerChannel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineException;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import com.yammer.httptunnel.state.BindState;
import com.yammer.httptunnel.util.TunnelIdGenerator;
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.server;
/**
* The server end of an HTTP tunnel, created by an
* {@link HttpTunnelServerChannelFactory}. Channels of this type are designed to
* emulate a normal TCP based server socket channel as far as is feasible within
* the limitations of the HTTP 1.0 protocol, and the usage patterns permitted by
* commonly used HTTP proxies and firewalls.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public class HttpTunnelServerChannel extends AbstractServerChannel implements ServerSocketChannel {
private static final InternalLogger LOG = InternalLoggerFactory.getInstance(HttpTunnelServerChannel.class);
private static final Random random;
static {
random = new Random();
}
private final String tunnelIdPrefix;
private final ConcurrentHashMap<String, HttpTunnelAcceptedChannel> tunnels;
private final ServerSocketChannel realChannel;
private final HttpTunnelServerChannelConfig config;
private final AtomicBoolean opened; | private final AtomicReference<BindState> bindState; |
reines/httptunnel | src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannel.java | // Path: src/main/java/com/yammer/httptunnel/state/BindState.java
// public enum BindState {
// /**
// * The channel is currently not bound to any address.
// */
// UNBOUND,
//
// /**
// * The channel is currently in the process of binding to a local address.
// */
// BINDING,
//
// /**
// * The channel is currently bound to a local address.
// */
// BOUND,
//
// /**
// * The channel is currently in the process of unbinding from a local
// * address.
// */
// UNBINDING;
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
| import java.net.InetSocketAddress;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.netty.channel.AbstractServerChannel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineException;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import com.yammer.httptunnel.state.BindState;
import com.yammer.httptunnel.util.TunnelIdGenerator; | unbindFuture.setSuccess();
return unbindFuture;
}
final ChannelFutureListener unbindListener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
bindState.set(BindState.UNBOUND);
Channels.fireChannelUnbound(HttpTunnelServerChannel.this);
if (unbindFuture != null)
unbindFuture.setSuccess();
}
else {
bindState.set(BindState.UNBOUND);
Channels.fireExceptionCaught(HttpTunnelServerChannel.this, future.getCause());
if (unbindFuture != null)
unbindFuture.setFailure(future.getCause());
}
}
};
realChannel.unbind().addListener(unbindListener);
return unbindFuture;
}
public HttpTunnelAcceptedChannel createTunnel(InetSocketAddress remoteAddress) { | // Path: src/main/java/com/yammer/httptunnel/state/BindState.java
// public enum BindState {
// /**
// * The channel is currently not bound to any address.
// */
// UNBOUND,
//
// /**
// * The channel is currently in the process of binding to a local address.
// */
// BINDING,
//
// /**
// * The channel is currently bound to a local address.
// */
// BOUND,
//
// /**
// * The channel is currently in the process of unbinding from a local
// * address.
// */
// UNBINDING;
// }
//
// Path: src/main/java/com/yammer/httptunnel/util/TunnelIdGenerator.java
// public interface TunnelIdGenerator {
//
// /**
// * Generates the next tunnel ID to be used, which must be unique (i.e.
// * ensure with high probability that it will not clash with an existing
// * tunnel ID). This method must be thread safe, and preferably lock free.
// */
// public String generateId();
// }
// Path: src/main/java/com/yammer/httptunnel/server/HttpTunnelServerChannel.java
import java.net.InetSocketAddress;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.netty.channel.AbstractServerChannel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineException;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.socket.ServerSocketChannel;
import org.jboss.netty.channel.socket.ServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import com.yammer.httptunnel.state.BindState;
import com.yammer.httptunnel.util.TunnelIdGenerator;
unbindFuture.setSuccess();
return unbindFuture;
}
final ChannelFutureListener unbindListener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
bindState.set(BindState.UNBOUND);
Channels.fireChannelUnbound(HttpTunnelServerChannel.this);
if (unbindFuture != null)
unbindFuture.setSuccess();
}
else {
bindState.set(BindState.UNBOUND);
Channels.fireExceptionCaught(HttpTunnelServerChannel.this, future.getCause());
if (unbindFuture != null)
unbindFuture.setFailure(future.getCause());
}
}
};
realChannel.unbind().addListener(unbindListener);
return unbindFuture;
}
public HttpTunnelAcceptedChannel createTunnel(InetSocketAddress remoteAddress) { | final TunnelIdGenerator tunnelIdGenerator = config.getTunnelIdGenerator(); |
reines/httptunnel | src/main/java/com/yammer/httptunnel/util/SaturationManager.java | // Path: src/main/java/com/yammer/httptunnel/state/SaturationStateChange.java
// public enum SaturationStateChange {
// /**
// * There was no change in the channels saturation state.
// */
// NO_CHANGE,
//
// /**
// * The channel is no longer saturated and writing can safely commence.
// */
// DESATURATED,
//
// /**
// * The channel has become saturated and writing should cease until it
// * becomes desaturated.
// */
// SATURATED;
// }
| import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import com.yammer.httptunnel.state.SaturationStateChange; | /*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.util;
/**
* This class is used to monitor the amount of data that has yet to be pushed to
* the underlying socket, in order to implement the "high/low water mark"
* facility that controls Channel.isWritable() and the interest ops of http
* tunnels.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public class SaturationManager {
private final AtomicLong desaturationPoint;
private final AtomicLong saturationPoint;
private final AtomicLong queueSize;
private final AtomicBoolean saturated;
public SaturationManager(long desaturationPoint, long saturationPoint) {
this.desaturationPoint = new AtomicLong(desaturationPoint);
this.saturationPoint = new AtomicLong(saturationPoint);
queueSize = new AtomicLong(0);
saturated = new AtomicBoolean(false);
}
| // Path: src/main/java/com/yammer/httptunnel/state/SaturationStateChange.java
// public enum SaturationStateChange {
// /**
// * There was no change in the channels saturation state.
// */
// NO_CHANGE,
//
// /**
// * The channel is no longer saturated and writing can safely commence.
// */
// DESATURATED,
//
// /**
// * The channel has become saturated and writing should cease until it
// * becomes desaturated.
// */
// SATURATED;
// }
// Path: src/main/java/com/yammer/httptunnel/util/SaturationManager.java
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import com.yammer.httptunnel.state.SaturationStateChange;
/*
* Copyright 2011 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.yammer.httptunnel.util;
/**
* This class is used to monitor the amount of data that has yet to be pushed to
* the underlying socket, in order to implement the "high/low water mark"
* facility that controls Channel.isWritable() and the interest ops of http
* tunnels.
*
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Iain McGinniss (iain.mcginniss@onedrum.com)
* @author Jamie Furness (jamie@onedrum.com)
* @author OneDrum Ltd.
*/
public class SaturationManager {
private final AtomicLong desaturationPoint;
private final AtomicLong saturationPoint;
private final AtomicLong queueSize;
private final AtomicBoolean saturated;
public SaturationManager(long desaturationPoint, long saturationPoint) {
this.desaturationPoint = new AtomicLong(desaturationPoint);
this.saturationPoint = new AtomicLong(saturationPoint);
queueSize = new AtomicLong(0);
saturated = new AtomicBoolean(false);
}
| public SaturationStateChange queueSizeChanged(long sizeDelta) { |
yanzhenjie/LiveSourceCode | CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/HttpExecutor.java
// public interface HttpExecutor {
//
// HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException;
//
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
| import android.content.Context;
import com.yanzhenjie.coolhttp.http.execute.HttpExecutor;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor; | /*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp.http;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class CoolHttp {
/**
* https://git.oschina.net/ysb/NoHttpUtil
*
* https://github.com/LiqiNew/NohttpRxUtils
*/
private static Context sContext;
private static HttpConfig sHttpConfig;
public static void initialize(Context context) {
initialize(context, new HttpConfig());
}
public static void initialize(Context context, HttpConfig httpConfig) {
sContext = context;
sHttpConfig = httpConfig;
}
private static void hasInitialize() {
if (sContext == null)
throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
}
| // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/HttpExecutor.java
// public interface HttpExecutor {
//
// HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException;
//
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java
import android.content.Context;
import com.yanzhenjie.coolhttp.http.execute.HttpExecutor;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor;
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp.http;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class CoolHttp {
/**
* https://git.oschina.net/ysb/NoHttpUtil
*
* https://github.com/LiqiNew/NohttpRxUtils
*/
private static Context sContext;
private static HttpConfig sHttpConfig;
public static void initialize(Context context) {
initialize(context, new HttpConfig());
}
public static void initialize(Context context, HttpConfig httpConfig) {
sContext = context;
sHttpConfig = httpConfig;
}
private static void hasInitialize() {
if (sContext == null)
throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
}
| public static HttpExecutor getHttpExecutor() { |
yanzhenjie/LiveSourceCode | CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/HttpExecutor.java
// public interface HttpExecutor {
//
// HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException;
//
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
| import android.content.Context;
import com.yanzhenjie.coolhttp.http.execute.HttpExecutor;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor; | sHttpConfig = httpConfig;
}
private static void hasInitialize() {
if (sContext == null)
throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
}
public static HttpExecutor getHttpExecutor() {
hasInitialize();
return sHttpConfig.httpExecutor;
}
public static int getConnectionTimeout() {
hasInitialize();
return sHttpConfig.connectionTimeout;
}
public static int getReadTimeout() {
hasInitialize();
return sHttpConfig.readTimeout;
}
public static class HttpConfig {
private HttpExecutor httpExecutor;
private int connectionTimeout;
private int readTimeout;
public HttpConfig() { | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/HttpExecutor.java
// public interface HttpExecutor {
//
// HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException;
//
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java
import android.content.Context;
import com.yanzhenjie.coolhttp.http.execute.HttpExecutor;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor;
sHttpConfig = httpConfig;
}
private static void hasInitialize() {
if (sContext == null)
throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
}
public static HttpExecutor getHttpExecutor() {
hasInitialize();
return sHttpConfig.httpExecutor;
}
public static int getConnectionTimeout() {
hasInitialize();
return sHttpConfig.connectionTimeout;
}
public static int getReadTimeout() {
hasInitialize();
return sHttpConfig.readTimeout;
}
public static class HttpConfig {
private HttpExecutor httpExecutor;
private int connectionTimeout;
private int readTimeout;
public HttpConfig() { | httpExecutor = OkHttpExecutor.getInstance(); |
yanzhenjie/LiveSourceCode | CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/StringRequest.java | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/utils/HeadUtils.java
// public class HeadUtils {
//
// public static String parseValue(Map<String, List<String>> responseHeader, String parentKey, String valueKey) {
// List<String> contentTypes = responseHeader.get(parentKey);
// if (contentTypes != null && contentTypes.size() > 0) {
// String contentType = contentTypes.get(0);
// StringTokenizer stringTokenizer = new StringTokenizer(contentType, ";");
// while (stringTokenizer.hasMoreTokens()) {
// String token = stringTokenizer.nextToken();
// if (token.contains(valueKey)) {
// String[] values = token.split("=");
// if (values.length > 1) {
// return values[1];
// }
// }
// }
// }
// return null;
// }
//
// }
| import android.text.TextUtils;
import com.yanzhenjie.coolhttp.http.utils.HeadUtils;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map; | /*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp.http;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class StringRequest extends Request<String> {
public StringRequest(String url, Method method) {
super(url, method);
setHeader("Accept", "text/html,application/xhtml+xml,application/xml;");
}
@Override
public String parseResponse(Map<String, List<String>> responseHeader, byte[] responseBody) {
return parseString(responseHeader, responseBody);
}
public static String parseString(Map<String, List<String>> responseHeader, byte[] responseBody) {
if (responseBody == null || responseBody.length <= 0) return "";
| // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/utils/HeadUtils.java
// public class HeadUtils {
//
// public static String parseValue(Map<String, List<String>> responseHeader, String parentKey, String valueKey) {
// List<String> contentTypes = responseHeader.get(parentKey);
// if (contentTypes != null && contentTypes.size() > 0) {
// String contentType = contentTypes.get(0);
// StringTokenizer stringTokenizer = new StringTokenizer(contentType, ";");
// while (stringTokenizer.hasMoreTokens()) {
// String token = stringTokenizer.nextToken();
// if (token.contains(valueKey)) {
// String[] values = token.split("=");
// if (values.length > 1) {
// return values[1];
// }
// }
// }
// }
// return null;
// }
//
// }
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/StringRequest.java
import android.text.TextUtils;
import com.yanzhenjie.coolhttp.http.utils.HeadUtils;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp.http;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class StringRequest extends Request<String> {
public StringRequest(String url, Method method) {
super(url, method);
setHeader("Accept", "text/html,application/xhtml+xml,application/xml;");
}
@Override
public String parseResponse(Map<String, List<String>> responseHeader, byte[] responseBody) {
return parseString(responseHeader, responseBody);
}
public static String parseString(Map<String, List<String>> responseHeader, byte[] responseBody) {
if (responseBody == null || responseBody.length <= 0) return "";
| String charset = HeadUtils.parseValue(responseHeader, "Content-Type", "charset"); |
yanzhenjie/LiveSourceCode | CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/Request.java | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/utils/CountOutputStream.java
// public class CountOutputStream extends OutputStream {
//
// private AtomicLong atomicLong = new AtomicLong();
//
// @Override
// public void write(int b) throws IOException {
// atomicLong.addAndGet(1);
// }
//
// @Override
// public void write(byte[] b) throws IOException {
// atomicLong.addAndGet(b.length);
// }
//
// @Override
// public void write(byte[] b, int off, int len) throws IOException {
// atomicLong.addAndGet(len);
// }
//
// public void write(long length) {
// atomicLong.addAndGet(length);
// }
//
// public long get() {
// return atomicLong.get();
// }
// }
| import android.text.TextUtils;
import com.yanzhenjie.coolhttp.http.utils.CountOutputStream;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory; | // --boundary(start boundary)
// Content-Disposition: form-data; name="key" // key相当于url?key=value中的key
// Content-Type: text/plain
// 换行...
// Write String
// --boundary--(end boundary)
if (!TextUtils.isEmpty(contentType)) return contentType;
else if (needFormData())
return "multipart/form-data; boundary=" + boundary;
else
return "application/x-www-form-urlencoded";
}
private boolean needFormData() {
if (formData) return true;
for (KeyValue requestParam : requestParams) {
Object value = requestParam.getValue();
if (value instanceof Binary) return true;
}
return false;
}
/**
* 统计Content-Length。
*
* @return
* @throws Exception
*/
long getContentLength() throws Exception { | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/utils/CountOutputStream.java
// public class CountOutputStream extends OutputStream {
//
// private AtomicLong atomicLong = new AtomicLong();
//
// @Override
// public void write(int b) throws IOException {
// atomicLong.addAndGet(1);
// }
//
// @Override
// public void write(byte[] b) throws IOException {
// atomicLong.addAndGet(b.length);
// }
//
// @Override
// public void write(byte[] b, int off, int len) throws IOException {
// atomicLong.addAndGet(len);
// }
//
// public void write(long length) {
// atomicLong.addAndGet(length);
// }
//
// public long get() {
// return atomicLong.get();
// }
// }
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/Request.java
import android.text.TextUtils;
import com.yanzhenjie.coolhttp.http.utils.CountOutputStream;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
// --boundary(start boundary)
// Content-Disposition: form-data; name="key" // key相当于url?key=value中的key
// Content-Type: text/plain
// 换行...
// Write String
// --boundary--(end boundary)
if (!TextUtils.isEmpty(contentType)) return contentType;
else if (needFormData())
return "multipart/form-data; boundary=" + boundary;
else
return "application/x-www-form-urlencoded";
}
private boolean needFormData() {
if (formData) return true;
for (KeyValue requestParam : requestParams) {
Object value = requestParam.getValue();
if (value instanceof Binary) return true;
}
return false;
}
/**
* 统计Content-Length。
*
* @return
* @throws Exception
*/
long getContentLength() throws Exception { | CountOutputStream outputStream = new CountOutputStream(); |
yanzhenjie/LiveSourceCode | CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/App.java | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java
// public class CoolHttp {
//
//
// /**
// * https://git.oschina.net/ysb/NoHttpUtil
// *
// * https://github.com/LiqiNew/NohttpRxUtils
// */
//
// private static Context sContext;
// private static HttpConfig sHttpConfig;
//
// public static void initialize(Context context) {
// initialize(context, new HttpConfig());
// }
//
// public static void initialize(Context context, HttpConfig httpConfig) {
// sContext = context;
// sHttpConfig = httpConfig;
// }
//
// private static void hasInitialize() {
// if (sContext == null)
// throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
// }
//
// public static HttpExecutor getHttpExecutor() {
// hasInitialize();
// return sHttpConfig.httpExecutor;
// }
//
// public static int getConnectionTimeout() {
// hasInitialize();
// return sHttpConfig.connectionTimeout;
// }
//
// public static int getReadTimeout() {
// hasInitialize();
// return sHttpConfig.readTimeout;
// }
//
// public static class HttpConfig {
//
// private HttpExecutor httpExecutor;
// private int connectionTimeout;
// private int readTimeout;
//
// public HttpConfig() {
// httpExecutor = OkHttpExecutor.getInstance();
// connectionTimeout = 8 * 1000;
// readTimeout = 8 * 1000;
// }
//
// public HttpConfig setHttpExecutor(HttpExecutor httpExecutor) {
// this.httpExecutor = httpExecutor;
// return this;
// }
//
// public HttpConfig setConnectionTimeout(int connectionTimeout) {
// this.connectionTimeout = connectionTimeout;
// return this;
// }
//
// public HttpConfig setReadTimeout(int readTimeout) {
// this.readTimeout = readTimeout;
// return this;
// }
// }
//
// // ---------- 同步请求 ----------- //
//
// /**
// * 同步请求。
// *
// * @param request 请求对象。
// * @param <T> 希望请求到的结果类型。
// * @return 响应封装对象。
// */
// public static <T> Response<T> syncRequest(Request<T> request) {
// return SyncExecutor.INSTANCE.execute(request);
// }
//
// // ---------- 异步请求 ----------- //
//
// /**
// * 异步请求。
// *
// * @param request 请求对象。
// * @param httpListener 回调接口。
// * @param <T> 希望请求到的结果类型。
// */
// public static <T> void asyncRequest(Request<T> request, HttpListener<T> httpListener) {
// AsyncExecutor.INSTANCE.execute(request, httpListener);
// }
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
| import android.app.Application;
import com.yanzhenjie.coolhttp.http.CoolHttp;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor; | /*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
// 第一种初始化方法。
// CoolHttp.initialize(this);
// 第二种初始化方法。 | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java
// public class CoolHttp {
//
//
// /**
// * https://git.oschina.net/ysb/NoHttpUtil
// *
// * https://github.com/LiqiNew/NohttpRxUtils
// */
//
// private static Context sContext;
// private static HttpConfig sHttpConfig;
//
// public static void initialize(Context context) {
// initialize(context, new HttpConfig());
// }
//
// public static void initialize(Context context, HttpConfig httpConfig) {
// sContext = context;
// sHttpConfig = httpConfig;
// }
//
// private static void hasInitialize() {
// if (sContext == null)
// throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
// }
//
// public static HttpExecutor getHttpExecutor() {
// hasInitialize();
// return sHttpConfig.httpExecutor;
// }
//
// public static int getConnectionTimeout() {
// hasInitialize();
// return sHttpConfig.connectionTimeout;
// }
//
// public static int getReadTimeout() {
// hasInitialize();
// return sHttpConfig.readTimeout;
// }
//
// public static class HttpConfig {
//
// private HttpExecutor httpExecutor;
// private int connectionTimeout;
// private int readTimeout;
//
// public HttpConfig() {
// httpExecutor = OkHttpExecutor.getInstance();
// connectionTimeout = 8 * 1000;
// readTimeout = 8 * 1000;
// }
//
// public HttpConfig setHttpExecutor(HttpExecutor httpExecutor) {
// this.httpExecutor = httpExecutor;
// return this;
// }
//
// public HttpConfig setConnectionTimeout(int connectionTimeout) {
// this.connectionTimeout = connectionTimeout;
// return this;
// }
//
// public HttpConfig setReadTimeout(int readTimeout) {
// this.readTimeout = readTimeout;
// return this;
// }
// }
//
// // ---------- 同步请求 ----------- //
//
// /**
// * 同步请求。
// *
// * @param request 请求对象。
// * @param <T> 希望请求到的结果类型。
// * @return 响应封装对象。
// */
// public static <T> Response<T> syncRequest(Request<T> request) {
// return SyncExecutor.INSTANCE.execute(request);
// }
//
// // ---------- 异步请求 ----------- //
//
// /**
// * 异步请求。
// *
// * @param request 请求对象。
// * @param httpListener 回调接口。
// * @param <T> 希望请求到的结果类型。
// */
// public static <T> void asyncRequest(Request<T> request, HttpListener<T> httpListener) {
// AsyncExecutor.INSTANCE.execute(request, httpListener);
// }
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/App.java
import android.app.Application;
import com.yanzhenjie.coolhttp.http.CoolHttp;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor;
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
// 第一种初始化方法。
// CoolHttp.initialize(this);
// 第二种初始化方法。 | CoolHttp.initialize( |
yanzhenjie/LiveSourceCode | CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/App.java | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java
// public class CoolHttp {
//
//
// /**
// * https://git.oschina.net/ysb/NoHttpUtil
// *
// * https://github.com/LiqiNew/NohttpRxUtils
// */
//
// private static Context sContext;
// private static HttpConfig sHttpConfig;
//
// public static void initialize(Context context) {
// initialize(context, new HttpConfig());
// }
//
// public static void initialize(Context context, HttpConfig httpConfig) {
// sContext = context;
// sHttpConfig = httpConfig;
// }
//
// private static void hasInitialize() {
// if (sContext == null)
// throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
// }
//
// public static HttpExecutor getHttpExecutor() {
// hasInitialize();
// return sHttpConfig.httpExecutor;
// }
//
// public static int getConnectionTimeout() {
// hasInitialize();
// return sHttpConfig.connectionTimeout;
// }
//
// public static int getReadTimeout() {
// hasInitialize();
// return sHttpConfig.readTimeout;
// }
//
// public static class HttpConfig {
//
// private HttpExecutor httpExecutor;
// private int connectionTimeout;
// private int readTimeout;
//
// public HttpConfig() {
// httpExecutor = OkHttpExecutor.getInstance();
// connectionTimeout = 8 * 1000;
// readTimeout = 8 * 1000;
// }
//
// public HttpConfig setHttpExecutor(HttpExecutor httpExecutor) {
// this.httpExecutor = httpExecutor;
// return this;
// }
//
// public HttpConfig setConnectionTimeout(int connectionTimeout) {
// this.connectionTimeout = connectionTimeout;
// return this;
// }
//
// public HttpConfig setReadTimeout(int readTimeout) {
// this.readTimeout = readTimeout;
// return this;
// }
// }
//
// // ---------- 同步请求 ----------- //
//
// /**
// * 同步请求。
// *
// * @param request 请求对象。
// * @param <T> 希望请求到的结果类型。
// * @return 响应封装对象。
// */
// public static <T> Response<T> syncRequest(Request<T> request) {
// return SyncExecutor.INSTANCE.execute(request);
// }
//
// // ---------- 异步请求 ----------- //
//
// /**
// * 异步请求。
// *
// * @param request 请求对象。
// * @param httpListener 回调接口。
// * @param <T> 希望请求到的结果类型。
// */
// public static <T> void asyncRequest(Request<T> request, HttpListener<T> httpListener) {
// AsyncExecutor.INSTANCE.execute(request, httpListener);
// }
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
| import android.app.Application;
import com.yanzhenjie.coolhttp.http.CoolHttp;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor; | /*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
// 第一种初始化方法。
// CoolHttp.initialize(this);
// 第二种初始化方法。
CoolHttp.initialize(
this,
new CoolHttp.HttpConfig()
.setConnectionTimeout(10 * 1000)
.setReadTimeout(20 * 1000) | // Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/CoolHttp.java
// public class CoolHttp {
//
//
// /**
// * https://git.oschina.net/ysb/NoHttpUtil
// *
// * https://github.com/LiqiNew/NohttpRxUtils
// */
//
// private static Context sContext;
// private static HttpConfig sHttpConfig;
//
// public static void initialize(Context context) {
// initialize(context, new HttpConfig());
// }
//
// public static void initialize(Context context, HttpConfig httpConfig) {
// sContext = context;
// sHttpConfig = httpConfig;
// }
//
// private static void hasInitialize() {
// if (sContext == null)
// throw new ExceptionInInitializerError("Please invoke CoolHttp.initialize(Application) in Application#onCreate()");
// }
//
// public static HttpExecutor getHttpExecutor() {
// hasInitialize();
// return sHttpConfig.httpExecutor;
// }
//
// public static int getConnectionTimeout() {
// hasInitialize();
// return sHttpConfig.connectionTimeout;
// }
//
// public static int getReadTimeout() {
// hasInitialize();
// return sHttpConfig.readTimeout;
// }
//
// public static class HttpConfig {
//
// private HttpExecutor httpExecutor;
// private int connectionTimeout;
// private int readTimeout;
//
// public HttpConfig() {
// httpExecutor = OkHttpExecutor.getInstance();
// connectionTimeout = 8 * 1000;
// readTimeout = 8 * 1000;
// }
//
// public HttpConfig setHttpExecutor(HttpExecutor httpExecutor) {
// this.httpExecutor = httpExecutor;
// return this;
// }
//
// public HttpConfig setConnectionTimeout(int connectionTimeout) {
// this.connectionTimeout = connectionTimeout;
// return this;
// }
//
// public HttpConfig setReadTimeout(int readTimeout) {
// this.readTimeout = readTimeout;
// return this;
// }
// }
//
// // ---------- 同步请求 ----------- //
//
// /**
// * 同步请求。
// *
// * @param request 请求对象。
// * @param <T> 希望请求到的结果类型。
// * @return 响应封装对象。
// */
// public static <T> Response<T> syncRequest(Request<T> request) {
// return SyncExecutor.INSTANCE.execute(request);
// }
//
// // ---------- 异步请求 ----------- //
//
// /**
// * 异步请求。
// *
// * @param request 请求对象。
// * @param httpListener 回调接口。
// * @param <T> 希望请求到的结果类型。
// */
// public static <T> void asyncRequest(Request<T> request, HttpListener<T> httpListener) {
// AsyncExecutor.INSTANCE.execute(request, httpListener);
// }
// }
//
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/http/execute/OkHttpExecutor.java
// public class OkHttpExecutor implements HttpExecutor {
//
//
// private static OkHttpExecutor instance;
//
// public static HttpExecutor getInstance() {
// if (instance == null)
// synchronized (OkHttpExecutor.class) {
// if (instance == null)
// instance = new OkHttpExecutor();
// }
// return instance;
// }
//
// private OkHttpClient okHttpClient;
//
// private OkHttpExecutor() {
// okHttpClient = new OkHttpClient();
// }
//
// @Override
// public HttpURLConnection openUrl(URL url, Proxy proxy) throws IOException {
// String protocol = url.getProtocol(); // http or https.
// OkHttpClient copy = okHttpClient.newBuilder().proxy(proxy).build();
//
// if (protocol.equals("http")) return new OkHttpURLConnection(url, copy);
// if (protocol.equals("https")) return new OkHttpsURLConnection(url, copy);
// throw new IllegalArgumentException("Unexpected protocol: " + protocol);
// }
//
// }
// Path: CoolHttp/app/src/main/java/com/yanzhenjie/coolhttp/App.java
import android.app.Application;
import com.yanzhenjie.coolhttp.http.CoolHttp;
import com.yanzhenjie.coolhttp.http.execute.OkHttpExecutor;
/*
* Copyright © Yan Zhenjie. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yanzhenjie.coolhttp;
/**
* Created by Yan Zhenjie on 2017/1/8.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
// 第一种初始化方法。
// CoolHttp.initialize(this);
// 第二种初始化方法。
CoolHttp.initialize(
this,
new CoolHttp.HttpConfig()
.setConnectionTimeout(10 * 1000)
.setReadTimeout(20 * 1000) | .setHttpExecutor(OkHttpExecutor.getInstance()) |
heremaps/here-aaa-java-sdk | here-oauth-client/src/main/java/com/here/account/auth/SignatureCalculator.java | // Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
| import static com.here.account.auth.SignatureMethod.ES512;
import com.here.account.util.OAuthConstants;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger; | for (String key : queryParams.keySet()) {
List<String> values = queryParams.get(key);
for (String value : values) {
parameterSet.add(key, value);
}
}
}
//sort the parameters by the key and format them into key=value concatenated with &
String parameterString = parameterSet.sortAndConcat();
//combine the signature base and parameters
signatureBaseString.append('&');
signatureBaseString.append(urlEncode(parameterString));
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("signatureBaseString=" + signatureBaseString);
}
return signatureBaseString.toString();
}
/**
* Sign the cipher text using the given key and the specified algorithm
* @param signatureBaseString the cipher text to be signed
* @param key the signing key
* @param signatureMethod signature method
* @return signed cipher text
*/
private static String generateSignature(String signatureBaseString, String key, SignatureMethod signatureMethod) {
//get the bytes from the signature base string | // Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
// Path: here-oauth-client/src/main/java/com/here/account/auth/SignatureCalculator.java
import static com.here.account.auth.SignatureMethod.ES512;
import com.here.account.util.OAuthConstants;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
for (String key : queryParams.keySet()) {
List<String> values = queryParams.get(key);
for (String value : values) {
parameterSet.add(key, value);
}
}
}
//sort the parameters by the key and format them into key=value concatenated with &
String parameterString = parameterSet.sortAndConcat();
//combine the signature base and parameters
signatureBaseString.append('&');
signatureBaseString.append(urlEncode(parameterString));
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("signatureBaseString=" + signatureBaseString);
}
return signatureBaseString.toString();
}
/**
* Sign the cipher text using the given key and the specified algorithm
* @param signatureBaseString the cipher text to be signed
* @param key the signing key
* @param signatureMethod signature method
* @return signed cipher text
*/
private static String generateSignature(String signatureBaseString, String key, SignatureMethod signatureMethod) {
//get the bytes from the signature base string | byte[] bytesToSign = signatureBaseString.getBytes(OAuthConstants.UTF_8_CHARSET); |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/oauth2/ClientCredentialsGrantRequestTest.java | // Path: here-oauth-client/src/main/java/com/here/account/util/JsonSerializer.java
// public class JsonSerializer {
//
// /**
// * The name of the UTF-8 {@link #CHARSET}.
// */
// public static final String CHARSET_STRING = "UTF-8";
//
// /**
// * Constant for the loaded UTF-8 Charset.
// */
// public static final Charset CHARSET = Charset.forName(CHARSET_STRING);
//
// private static ObjectMapper objectMapper = new ObjectMapper();
//
// static {
// objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// }
//
// /**
// * Converts the input JSON InputStream, to a Map<String, Object>.
// *
// * @param jsonInputStream the input stream to the JSON object
// * @return its Map representation
// * @throws IOException if trouble deserializing
// */
// public static Map<String, Object> toMap(InputStream jsonInputStream) throws IOException {
// return (HashMap<String, Object>) objectMapper.readValue(jsonInputStream, HashMap.class);
// }
//
// /**
// * Converts the input JSON InputStream, to a POJO of the class specified as pojoClass.
// *
// * @param <T> the type of the POJO
// * @param jsonInputStream the input stream to the JSON object
// * @param pojoClass the class to deserialize into
// * @return the instance of the pojoClass with member variables populated
// * @throws JsonParseException if trouble parsing
// * @throws JsonMappingException if trouble mapping
// * @throws IOException if trouble deserializing
// */
// public static <T> T toPojo (InputStream jsonInputStream, Class<T> pojoClass) throws JsonParseException, JsonMappingException, IOException {
// return objectMapper.readValue(jsonInputStream, pojoClass);
// }
//
// /**
// * Converts the input mapObject to its JSON String representation.
// *
// * @param mapObject the json's Map representation
// * @return the JSON String representation of the input.
// * @throws JsonProcessingException if an exception from the jackson serializer
// */
// public static String toJson(Map<String, Object> mapObject) throws JsonProcessingException {
// return objectMapper.writeValueAsString(mapObject);
// }
//
// /**
// * Converts the input POJO object to its JSON string.
// *
// * @param object the object to serialize into a JSON string.
// * @return the JSON string representation of the object.
// * @throws JsonProcessingException if there's trouble serializing object
// * to a JSON string.
// */
// public static String objectToJson(Object object) throws JsonProcessingException {
// return objectMapper.writeValueAsString(object);
// }
//
// /**
// * Writes the object to the specified outputStream as JSON.
// *
// * @param outputStream the OutputStream to which to write
// * @param object the object to write to the stream
// * @throws JsonGenerationException if trouble serializing
// * @throws JsonMappingException if trouble serializing
// * @throws IOException if I/O trouble writing to the stream
// */
// static void writeObjectToJson(OutputStream outputStream, Object object) throws JsonGenerationException, JsonMappingException, IOException {
// objectMapper.writeValue(outputStream, object);
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
| import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.here.account.util.JsonSerializer;
import com.here.account.util.OAuthConstants; | Map<String, Object> expectedMap = toMap(expectedJson);
assertTrue("expected json "+expectedMap+", actual "+jsonMap, expectedMap.equals(jsonMap));
}
@Test
public void test_ClientCredentialsGrantRequest_form() {
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new ClientCredentialsGrantRequest();
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
@Test
public void test_ClientCredentialsGrantRequest_form_expiresIn() throws IOException {
long expiresIn = 15;
String scope = "test scope";
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new
ClientCredentialsGrantRequest().setExpiresIn(expiresIn);
clientCredentialsGrantRequest.setScope(scope);
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
expectedForm.put("expires_in", Collections.singletonList(""+expiresIn));
expectedForm.put("scope", Collections.singletonList(scope));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
private Map<String, Object> toMap(String json) throws IOException { | // Path: here-oauth-client/src/main/java/com/here/account/util/JsonSerializer.java
// public class JsonSerializer {
//
// /**
// * The name of the UTF-8 {@link #CHARSET}.
// */
// public static final String CHARSET_STRING = "UTF-8";
//
// /**
// * Constant for the loaded UTF-8 Charset.
// */
// public static final Charset CHARSET = Charset.forName(CHARSET_STRING);
//
// private static ObjectMapper objectMapper = new ObjectMapper();
//
// static {
// objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// }
//
// /**
// * Converts the input JSON InputStream, to a Map<String, Object>.
// *
// * @param jsonInputStream the input stream to the JSON object
// * @return its Map representation
// * @throws IOException if trouble deserializing
// */
// public static Map<String, Object> toMap(InputStream jsonInputStream) throws IOException {
// return (HashMap<String, Object>) objectMapper.readValue(jsonInputStream, HashMap.class);
// }
//
// /**
// * Converts the input JSON InputStream, to a POJO of the class specified as pojoClass.
// *
// * @param <T> the type of the POJO
// * @param jsonInputStream the input stream to the JSON object
// * @param pojoClass the class to deserialize into
// * @return the instance of the pojoClass with member variables populated
// * @throws JsonParseException if trouble parsing
// * @throws JsonMappingException if trouble mapping
// * @throws IOException if trouble deserializing
// */
// public static <T> T toPojo (InputStream jsonInputStream, Class<T> pojoClass) throws JsonParseException, JsonMappingException, IOException {
// return objectMapper.readValue(jsonInputStream, pojoClass);
// }
//
// /**
// * Converts the input mapObject to its JSON String representation.
// *
// * @param mapObject the json's Map representation
// * @return the JSON String representation of the input.
// * @throws JsonProcessingException if an exception from the jackson serializer
// */
// public static String toJson(Map<String, Object> mapObject) throws JsonProcessingException {
// return objectMapper.writeValueAsString(mapObject);
// }
//
// /**
// * Converts the input POJO object to its JSON string.
// *
// * @param object the object to serialize into a JSON string.
// * @return the JSON string representation of the object.
// * @throws JsonProcessingException if there's trouble serializing object
// * to a JSON string.
// */
// public static String objectToJson(Object object) throws JsonProcessingException {
// return objectMapper.writeValueAsString(object);
// }
//
// /**
// * Writes the object to the specified outputStream as JSON.
// *
// * @param outputStream the OutputStream to which to write
// * @param object the object to write to the stream
// * @throws JsonGenerationException if trouble serializing
// * @throws JsonMappingException if trouble serializing
// * @throws IOException if I/O trouble writing to the stream
// */
// static void writeObjectToJson(OutputStream outputStream, Object object) throws JsonGenerationException, JsonMappingException, IOException {
// objectMapper.writeValue(outputStream, object);
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
// Path: here-oauth-client/src/test/java/com/here/account/oauth2/ClientCredentialsGrantRequestTest.java
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.here.account.util.JsonSerializer;
import com.here.account.util.OAuthConstants;
Map<String, Object> expectedMap = toMap(expectedJson);
assertTrue("expected json "+expectedMap+", actual "+jsonMap, expectedMap.equals(jsonMap));
}
@Test
public void test_ClientCredentialsGrantRequest_form() {
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new ClientCredentialsGrantRequest();
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
@Test
public void test_ClientCredentialsGrantRequest_form_expiresIn() throws IOException {
long expiresIn = 15;
String scope = "test scope";
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new
ClientCredentialsGrantRequest().setExpiresIn(expiresIn);
clientCredentialsGrantRequest.setScope(scope);
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
expectedForm.put("expires_in", Collections.singletonList(""+expiresIn));
expectedForm.put("scope", Collections.singletonList(scope));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
private Map<String, Object> toMap(String json) throws IOException { | byte[] bytes = json.getBytes(OAuthConstants.UTF_8_CHARSET); |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/oauth2/ClientCredentialsGrantRequestTest.java | // Path: here-oauth-client/src/main/java/com/here/account/util/JsonSerializer.java
// public class JsonSerializer {
//
// /**
// * The name of the UTF-8 {@link #CHARSET}.
// */
// public static final String CHARSET_STRING = "UTF-8";
//
// /**
// * Constant for the loaded UTF-8 Charset.
// */
// public static final Charset CHARSET = Charset.forName(CHARSET_STRING);
//
// private static ObjectMapper objectMapper = new ObjectMapper();
//
// static {
// objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// }
//
// /**
// * Converts the input JSON InputStream, to a Map<String, Object>.
// *
// * @param jsonInputStream the input stream to the JSON object
// * @return its Map representation
// * @throws IOException if trouble deserializing
// */
// public static Map<String, Object> toMap(InputStream jsonInputStream) throws IOException {
// return (HashMap<String, Object>) objectMapper.readValue(jsonInputStream, HashMap.class);
// }
//
// /**
// * Converts the input JSON InputStream, to a POJO of the class specified as pojoClass.
// *
// * @param <T> the type of the POJO
// * @param jsonInputStream the input stream to the JSON object
// * @param pojoClass the class to deserialize into
// * @return the instance of the pojoClass with member variables populated
// * @throws JsonParseException if trouble parsing
// * @throws JsonMappingException if trouble mapping
// * @throws IOException if trouble deserializing
// */
// public static <T> T toPojo (InputStream jsonInputStream, Class<T> pojoClass) throws JsonParseException, JsonMappingException, IOException {
// return objectMapper.readValue(jsonInputStream, pojoClass);
// }
//
// /**
// * Converts the input mapObject to its JSON String representation.
// *
// * @param mapObject the json's Map representation
// * @return the JSON String representation of the input.
// * @throws JsonProcessingException if an exception from the jackson serializer
// */
// public static String toJson(Map<String, Object> mapObject) throws JsonProcessingException {
// return objectMapper.writeValueAsString(mapObject);
// }
//
// /**
// * Converts the input POJO object to its JSON string.
// *
// * @param object the object to serialize into a JSON string.
// * @return the JSON string representation of the object.
// * @throws JsonProcessingException if there's trouble serializing object
// * to a JSON string.
// */
// public static String objectToJson(Object object) throws JsonProcessingException {
// return objectMapper.writeValueAsString(object);
// }
//
// /**
// * Writes the object to the specified outputStream as JSON.
// *
// * @param outputStream the OutputStream to which to write
// * @param object the object to write to the stream
// * @throws JsonGenerationException if trouble serializing
// * @throws JsonMappingException if trouble serializing
// * @throws IOException if I/O trouble writing to the stream
// */
// static void writeObjectToJson(OutputStream outputStream, Object object) throws JsonGenerationException, JsonMappingException, IOException {
// objectMapper.writeValue(outputStream, object);
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
| import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.here.account.util.JsonSerializer;
import com.here.account.util.OAuthConstants; | @Test
public void test_ClientCredentialsGrantRequest_form() {
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new ClientCredentialsGrantRequest();
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
@Test
public void test_ClientCredentialsGrantRequest_form_expiresIn() throws IOException {
long expiresIn = 15;
String scope = "test scope";
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new
ClientCredentialsGrantRequest().setExpiresIn(expiresIn);
clientCredentialsGrantRequest.setScope(scope);
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
expectedForm.put("expires_in", Collections.singletonList(""+expiresIn));
expectedForm.put("scope", Collections.singletonList(scope));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
private Map<String, Object> toMap(String json) throws IOException {
byte[] bytes = json.getBytes(OAuthConstants.UTF_8_CHARSET);
ByteArrayInputStream jsonInputStream = null;
try {
jsonInputStream = new ByteArrayInputStream(bytes); | // Path: here-oauth-client/src/main/java/com/here/account/util/JsonSerializer.java
// public class JsonSerializer {
//
// /**
// * The name of the UTF-8 {@link #CHARSET}.
// */
// public static final String CHARSET_STRING = "UTF-8";
//
// /**
// * Constant for the loaded UTF-8 Charset.
// */
// public static final Charset CHARSET = Charset.forName(CHARSET_STRING);
//
// private static ObjectMapper objectMapper = new ObjectMapper();
//
// static {
// objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// }
//
// /**
// * Converts the input JSON InputStream, to a Map<String, Object>.
// *
// * @param jsonInputStream the input stream to the JSON object
// * @return its Map representation
// * @throws IOException if trouble deserializing
// */
// public static Map<String, Object> toMap(InputStream jsonInputStream) throws IOException {
// return (HashMap<String, Object>) objectMapper.readValue(jsonInputStream, HashMap.class);
// }
//
// /**
// * Converts the input JSON InputStream, to a POJO of the class specified as pojoClass.
// *
// * @param <T> the type of the POJO
// * @param jsonInputStream the input stream to the JSON object
// * @param pojoClass the class to deserialize into
// * @return the instance of the pojoClass with member variables populated
// * @throws JsonParseException if trouble parsing
// * @throws JsonMappingException if trouble mapping
// * @throws IOException if trouble deserializing
// */
// public static <T> T toPojo (InputStream jsonInputStream, Class<T> pojoClass) throws JsonParseException, JsonMappingException, IOException {
// return objectMapper.readValue(jsonInputStream, pojoClass);
// }
//
// /**
// * Converts the input mapObject to its JSON String representation.
// *
// * @param mapObject the json's Map representation
// * @return the JSON String representation of the input.
// * @throws JsonProcessingException if an exception from the jackson serializer
// */
// public static String toJson(Map<String, Object> mapObject) throws JsonProcessingException {
// return objectMapper.writeValueAsString(mapObject);
// }
//
// /**
// * Converts the input POJO object to its JSON string.
// *
// * @param object the object to serialize into a JSON string.
// * @return the JSON string representation of the object.
// * @throws JsonProcessingException if there's trouble serializing object
// * to a JSON string.
// */
// public static String objectToJson(Object object) throws JsonProcessingException {
// return objectMapper.writeValueAsString(object);
// }
//
// /**
// * Writes the object to the specified outputStream as JSON.
// *
// * @param outputStream the OutputStream to which to write
// * @param object the object to write to the stream
// * @throws JsonGenerationException if trouble serializing
// * @throws JsonMappingException if trouble serializing
// * @throws IOException if I/O trouble writing to the stream
// */
// static void writeObjectToJson(OutputStream outputStream, Object object) throws JsonGenerationException, JsonMappingException, IOException {
// objectMapper.writeValue(outputStream, object);
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
// Path: here-oauth-client/src/test/java/com/here/account/oauth2/ClientCredentialsGrantRequestTest.java
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.here.account.util.JsonSerializer;
import com.here.account.util.OAuthConstants;
@Test
public void test_ClientCredentialsGrantRequest_form() {
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new ClientCredentialsGrantRequest();
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
@Test
public void test_ClientCredentialsGrantRequest_form_expiresIn() throws IOException {
long expiresIn = 15;
String scope = "test scope";
ClientCredentialsGrantRequest clientCredentialsGrantRequest = new
ClientCredentialsGrantRequest().setExpiresIn(expiresIn);
clientCredentialsGrantRequest.setScope(scope);
Map<String, List<String>> form = clientCredentialsGrantRequest.toFormParams();
Map<String, List<String>> expectedForm = new HashMap<String, List<String>>();
expectedForm.put("grant_type", Collections.singletonList("client_credentials"));
expectedForm.put("expires_in", Collections.singletonList(""+expiresIn));
expectedForm.put("scope", Collections.singletonList(scope));
assertTrue("expected form "+expectedForm+", actual "+form, expectedForm.equals(form));
}
private Map<String, Object> toMap(String json) throws IOException {
byte[] bytes = json.getBytes(OAuthConstants.UTF_8_CHARSET);
ByteArrayInputStream jsonInputStream = null;
try {
jsonInputStream = new ByteArrayInputStream(bytes); | return JsonSerializer.toMap(jsonInputStream); |
heremaps/here-aaa-java-sdk | here-oauth-client/src/main/java/com/here/account/oauth2/retry/RetryExecutor.java | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public interface HttpProvider extends Closeable {
//
// /**
// * Wrapper for an HTTP request.
// */
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// /**
// * Wrapper for authorizing HTTP requests.
// */
// public static interface HttpRequestAuthorizer {
//
// /**
// * Computes and adds a signature or token to the request as appropriate
// * for the authentication or authorization scheme.
// *
// * @param httpRequest the HttpRequest under construction,
// * to which to attach authorization
// * @param method the HTTP method
// * @param url the URL of the request
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// */
// void authorize(HttpRequest httpRequest, String method, String url,
// Map<String, List<String>> formParams);
//
// }
//
// /**
// * Wrapper for HTTP responses.
// */
// public static interface HttpResponse {
//
// /**
// * Returns the HTTP response status code.
// *
// * @return the HTTP response status code as an int
// */
// int getStatusCode();
//
// /**
// * Returns the HTTP Content-Length header value.
// * The content length of the response body.
// *
// * @return the content length of the response body.
// */
// long getContentLength();
//
// /**
// * Get the response body, as an <tt>InputStream</tt>.
// *
// * @return if there was a response entity, returns the InputStream reading bytes
// * from that response entity.
// * otherwise, if there was no response entity, this method returns null.
// * @throws IOException if there is I/O trouble
// */
// InputStream getResponseBody() throws IOException;
//
// /**
// * Returns all the headers from the response
// * @return returns a Map of headers if the method implementation returns the headers
// * or throws Unsupported Operation Exception if the method is not implemented
// */
//
// default Map<String, List<String>> getHeaders() {
// throw new UnsupportedOperationException();
// }
//
// }
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and requestBodyJson.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param requestBodyJson the
// * Content-Type: application/json
// * JSON request body.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url, String requestBodyJson);
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and formParams.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url,
// Map<String, List<String>> formParams);
//
// /**
// * Execute the <tt>httpRequest</tt>.
// * Implementing classes would commonly invoke or schedule a RESTful HTTPS API call
// * over the wire to the configured Service as part of <tt>execute</tt>.
// *
// * @param httpRequest the HttpRequest
// * @return the HttpResponse to the request
// * @throws HttpException if there is trouble executing the httpRequest
// * @throws IOException if there is I/O trouble executing the httpRequest
// */
// HttpResponse execute(HttpRequest httpRequest) throws HttpException, IOException;
//
// }
| import com.here.account.http.HttpProvider;
import java.util.logging.Logger; | package com.here.account.oauth2.retry;
/**
* A {@code RetryExecutor} provides a mechanisms to execute a {@link Retryable}
* and will retry on failure according to an implementation specific retry policy.
* */
public class RetryExecutor {
private final RetryPolicy retryPolicy;
private static final Logger LOGGER = Logger.getLogger(RetryExecutor.class.getName());
public RetryExecutor(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
}
/**
* Execute the given {@link Retryable} until retry policy decides to give up.
* @param retryable the {@link Retryable} to execute
* @return http response return from {@code Retryable}
* @throws Exception
*/ | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public interface HttpProvider extends Closeable {
//
// /**
// * Wrapper for an HTTP request.
// */
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// /**
// * Wrapper for authorizing HTTP requests.
// */
// public static interface HttpRequestAuthorizer {
//
// /**
// * Computes and adds a signature or token to the request as appropriate
// * for the authentication or authorization scheme.
// *
// * @param httpRequest the HttpRequest under construction,
// * to which to attach authorization
// * @param method the HTTP method
// * @param url the URL of the request
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// */
// void authorize(HttpRequest httpRequest, String method, String url,
// Map<String, List<String>> formParams);
//
// }
//
// /**
// * Wrapper for HTTP responses.
// */
// public static interface HttpResponse {
//
// /**
// * Returns the HTTP response status code.
// *
// * @return the HTTP response status code as an int
// */
// int getStatusCode();
//
// /**
// * Returns the HTTP Content-Length header value.
// * The content length of the response body.
// *
// * @return the content length of the response body.
// */
// long getContentLength();
//
// /**
// * Get the response body, as an <tt>InputStream</tt>.
// *
// * @return if there was a response entity, returns the InputStream reading bytes
// * from that response entity.
// * otherwise, if there was no response entity, this method returns null.
// * @throws IOException if there is I/O trouble
// */
// InputStream getResponseBody() throws IOException;
//
// /**
// * Returns all the headers from the response
// * @return returns a Map of headers if the method implementation returns the headers
// * or throws Unsupported Operation Exception if the method is not implemented
// */
//
// default Map<String, List<String>> getHeaders() {
// throw new UnsupportedOperationException();
// }
//
// }
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and requestBodyJson.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param requestBodyJson the
// * Content-Type: application/json
// * JSON request body.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url, String requestBodyJson);
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and formParams.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url,
// Map<String, List<String>> formParams);
//
// /**
// * Execute the <tt>httpRequest</tt>.
// * Implementing classes would commonly invoke or schedule a RESTful HTTPS API call
// * over the wire to the configured Service as part of <tt>execute</tt>.
// *
// * @param httpRequest the HttpRequest
// * @return the HttpResponse to the request
// * @throws HttpException if there is trouble executing the httpRequest
// * @throws IOException if there is I/O trouble executing the httpRequest
// */
// HttpResponse execute(HttpRequest httpRequest) throws HttpException, IOException;
//
// }
// Path: here-oauth-client/src/main/java/com/here/account/oauth2/retry/RetryExecutor.java
import com.here.account.http.HttpProvider;
import java.util.logging.Logger;
package com.here.account.oauth2.retry;
/**
* A {@code RetryExecutor} provides a mechanisms to execute a {@link Retryable}
* and will retry on failure according to an implementation specific retry policy.
* */
public class RetryExecutor {
private final RetryPolicy retryPolicy;
private static final Logger LOGGER = Logger.getLogger(RetryExecutor.class.getName());
public RetryExecutor(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
}
/**
* Execute the given {@link Retryable} until retry policy decides to give up.
* @param retryable the {@link Retryable} to execute
* @return http response return from {@code Retryable}
* @throws Exception
*/ | public HttpProvider.HttpResponse execute(Retryable retryable) throws Exception { |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/auth/SignatureCalculatorTest.java | // Path: here-oauth-client/src/main/java/com/here/account/auth/SignatureCalculator.java
// public static final String ELLIPTIC_CURVE_ALGORITHM = "EC";
| import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.oauth.ConsumerKey;
import com.ning.http.client.oauth.OAuthSignatureCalculator;
import com.ning.http.client.oauth.RequestToken;
import org.junit.Test;
import java.security.*;
import java.security.spec.*;
import java.util.*;
import static com.here.account.auth.SignatureCalculator.ELLIPTIC_CURVE_ALGORITHM;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | expectedAuthHeader.equals(authHeader));
}
@Test
public void testSignatureES512WithBaseUrlWithPort(){
KeyPair pair = generateES512KeyPair();
final byte[] keyBytes = pair.getPrivate().getEncoded();
String keyBase64 = Base64.getEncoder().encodeToString(keyBytes);
SignatureCalculator sc = new SignatureCalculator(consumerKey, keyBase64);
String signature = sc.calculateSignature(method, baseURLWithPort, timestamp, nonce, SignatureMethod.ES512, params, params);
String publicKeyBase64 = Base64.getEncoder().encodeToString(pair.getPublic().getEncoded());
boolean verified = SignatureCalculator.verifySignature(consumerKey, method, baseURLWithPort, timestamp, nonce, SignatureMethod.ES512, params, params, signature, publicKeyBase64);
assertTrue(verified);
}
@Test
public void testVerifyES512() {
String cipherText = "testing public key and signature encryption";
String publicKeyBase64 = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQA2GcrZ94UbrYCsJo6sHOCnw4r5t5xSuX0x3LZPlRxA8dXziN1f1z2qUnudmI69JeEeX8JAfuu8kvRx4bjYnTVIasAO9P2V9eWWOxgfzGaC09JGBFN48XgI++9JNuS50DiHtSeSuM2kYTehHhj22Bj5iNlju1j1BbsAc1PS79G2pOpoFs=";
String signature = "MIGIAkIAz0ZVhsjWnbmdZkBHP7wl5u5q4qN1K5bFgHNRvZeh4lYxpuUg60vncYZLwBM4zHev1F4bSkLqudhtAt8arwrLs1YCQgFQrQXvoSsAfO/gK7IEQXEFK1UGN4RDnVQRpKaZiKDbOCY2qZ3AyGeaydrnoc6o0RdHzeuJaj9Or2YjqE7PjnwvSg==";
assertTrue(SignatureCalculator.verifySignature(cipherText, SignatureMethod.ES512, signature, publicKeyBase64));
}
public static KeyPair generateES512KeyPair() {
try {
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp521r1"); | // Path: here-oauth-client/src/main/java/com/here/account/auth/SignatureCalculator.java
// public static final String ELLIPTIC_CURVE_ALGORITHM = "EC";
// Path: here-oauth-client/src/test/java/com/here/account/auth/SignatureCalculatorTest.java
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.oauth.ConsumerKey;
import com.ning.http.client.oauth.OAuthSignatureCalculator;
import com.ning.http.client.oauth.RequestToken;
import org.junit.Test;
import java.security.*;
import java.security.spec.*;
import java.util.*;
import static com.here.account.auth.SignatureCalculator.ELLIPTIC_CURVE_ALGORITHM;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
expectedAuthHeader.equals(authHeader));
}
@Test
public void testSignatureES512WithBaseUrlWithPort(){
KeyPair pair = generateES512KeyPair();
final byte[] keyBytes = pair.getPrivate().getEncoded();
String keyBase64 = Base64.getEncoder().encodeToString(keyBytes);
SignatureCalculator sc = new SignatureCalculator(consumerKey, keyBase64);
String signature = sc.calculateSignature(method, baseURLWithPort, timestamp, nonce, SignatureMethod.ES512, params, params);
String publicKeyBase64 = Base64.getEncoder().encodeToString(pair.getPublic().getEncoded());
boolean verified = SignatureCalculator.verifySignature(consumerKey, method, baseURLWithPort, timestamp, nonce, SignatureMethod.ES512, params, params, signature, publicKeyBase64);
assertTrue(verified);
}
@Test
public void testVerifyES512() {
String cipherText = "testing public key and signature encryption";
String publicKeyBase64 = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQA2GcrZ94UbrYCsJo6sHOCnw4r5t5xSuX0x3LZPlRxA8dXziN1f1z2qUnudmI69JeEeX8JAfuu8kvRx4bjYnTVIasAO9P2V9eWWOxgfzGaC09JGBFN48XgI++9JNuS50DiHtSeSuM2kYTehHhj22Bj5iNlju1j1BbsAc1PS79G2pOpoFs=";
String signature = "MIGIAkIAz0ZVhsjWnbmdZkBHP7wl5u5q4qN1K5bFgHNRvZeh4lYxpuUg60vncYZLwBM4zHev1F4bSkLqudhtAt8arwrLs1YCQgFQrQXvoSsAfO/gK7IEQXEFK1UGN4RDnVQRpKaZiKDbOCY2qZ3AyGeaydrnoc6o0RdHzeuJaj9Or2YjqE7PjnwvSg==";
assertTrue(SignatureCalculator.verifySignature(cipherText, SignatureMethod.ES512, signature, publicKeyBase64));
}
public static KeyPair generateES512KeyPair() {
try {
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp521r1"); | KeyPairGenerator kpg = KeyPairGenerator.getInstance(ELLIPTIC_CURVE_ALGORITHM); |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/oauth2/FileAccessTokenResponseTest.java | // Path: here-oauth-client/src/main/java/com/here/account/util/JacksonSerializer.java
// public class JacksonSerializer implements Serializer {
//
// public JacksonSerializer() {
// }
//
// /**
// * {@inheritDoc}
// */
// public Map<String, Object> jsonToMap(InputStream jsonInputStream) {
// try {
// return JsonSerializer.toMap(jsonInputStream);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public <T> T jsonToPojo(InputStream jsonInputStream, Class<T> pojoClass) {
// try {
// return JsonSerializer.toPojo(jsonInputStream, pojoClass);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public String objectToJson(Object object) {
// try {
// return JsonSerializer.objectToJson(object);
// } catch (JsonProcessingException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
// @Override
// public void writeObjectToJson(OutputStream outputStream, Object object) {
// try {
// JsonSerializer.writeObjectToJson(outputStream, object);
// } catch (IOException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Serializer.java
// public interface Serializer {
//
// /**
// * Reads from the input jsonInputStream containing bytes from a JSON stream,
// * and returns the corresponding Map<String, Object>.
// *
// * @param jsonInputStream the input stream
// * @return the corresponding deserialized Map<String, Object>
// */
// Map<String, Object> jsonToMap(InputStream jsonInputStream);
//
// <T> T jsonToPojo (InputStream jsonInputStream, Class<T> pojoClass);
//
// String objectToJson(Object object);
//
// void writeObjectToJson(OutputStream outputStream, Object object);
//
// }
| import static org.junit.Assert.assertTrue;
import com.here.account.util.JacksonSerializer;
import com.here.account.util.Serializer;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; |
/*
* Copyright (c) 2018 HERE Europe B.V.
*
* 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.here.account.oauth2;
public class FileAccessTokenResponseTest {
private FileAccessTokenResponse response;
private File tmpFile; | // Path: here-oauth-client/src/main/java/com/here/account/util/JacksonSerializer.java
// public class JacksonSerializer implements Serializer {
//
// public JacksonSerializer() {
// }
//
// /**
// * {@inheritDoc}
// */
// public Map<String, Object> jsonToMap(InputStream jsonInputStream) {
// try {
// return JsonSerializer.toMap(jsonInputStream);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public <T> T jsonToPojo(InputStream jsonInputStream, Class<T> pojoClass) {
// try {
// return JsonSerializer.toPojo(jsonInputStream, pojoClass);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public String objectToJson(Object object) {
// try {
// return JsonSerializer.objectToJson(object);
// } catch (JsonProcessingException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
// @Override
// public void writeObjectToJson(OutputStream outputStream, Object object) {
// try {
// JsonSerializer.writeObjectToJson(outputStream, object);
// } catch (IOException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Serializer.java
// public interface Serializer {
//
// /**
// * Reads from the input jsonInputStream containing bytes from a JSON stream,
// * and returns the corresponding Map<String, Object>.
// *
// * @param jsonInputStream the input stream
// * @return the corresponding deserialized Map<String, Object>
// */
// Map<String, Object> jsonToMap(InputStream jsonInputStream);
//
// <T> T jsonToPojo (InputStream jsonInputStream, Class<T> pojoClass);
//
// String objectToJson(Object object);
//
// void writeObjectToJson(OutputStream outputStream, Object object);
//
// }
// Path: here-oauth-client/src/test/java/com/here/account/oauth2/FileAccessTokenResponseTest.java
import static org.junit.Assert.assertTrue;
import com.here.account.util.JacksonSerializer;
import com.here.account.util.Serializer;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/*
* Copyright (c) 2018 HERE Europe B.V.
*
* 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.here.account.oauth2;
public class FileAccessTokenResponseTest {
private FileAccessTokenResponse response;
private File tmpFile; | private Serializer serializer; |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/oauth2/FileAccessTokenResponseTest.java | // Path: here-oauth-client/src/main/java/com/here/account/util/JacksonSerializer.java
// public class JacksonSerializer implements Serializer {
//
// public JacksonSerializer() {
// }
//
// /**
// * {@inheritDoc}
// */
// public Map<String, Object> jsonToMap(InputStream jsonInputStream) {
// try {
// return JsonSerializer.toMap(jsonInputStream);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public <T> T jsonToPojo(InputStream jsonInputStream, Class<T> pojoClass) {
// try {
// return JsonSerializer.toPojo(jsonInputStream, pojoClass);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public String objectToJson(Object object) {
// try {
// return JsonSerializer.objectToJson(object);
// } catch (JsonProcessingException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
// @Override
// public void writeObjectToJson(OutputStream outputStream, Object object) {
// try {
// JsonSerializer.writeObjectToJson(outputStream, object);
// } catch (IOException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Serializer.java
// public interface Serializer {
//
// /**
// * Reads from the input jsonInputStream containing bytes from a JSON stream,
// * and returns the corresponding Map<String, Object>.
// *
// * @param jsonInputStream the input stream
// * @return the corresponding deserialized Map<String, Object>
// */
// Map<String, Object> jsonToMap(InputStream jsonInputStream);
//
// <T> T jsonToPojo (InputStream jsonInputStream, Class<T> pojoClass);
//
// String objectToJson(Object object);
//
// void writeObjectToJson(OutputStream outputStream, Object object);
//
// }
| import static org.junit.Assert.assertTrue;
import com.here.account.util.JacksonSerializer;
import com.here.account.util.Serializer;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; |
/**
* Tests the timestamp and relative timings for a FileAccessTokenResponse,
* when read multiple times from the same previously-serialized file,
* over increasing clock time.
*
* @throws IOException if IO trouble
* @throws InterruptedException if interrupted during sleep
*/
@Test
public void test_timings_sameFile_multipleReads() throws IOException, InterruptedException {
String accessToken = "my-access-token";
String tokenType = "bearer";
Long expiresIn = 45L;
String refreshToken = null;
String idToken = null;
Long exp = (System.currentTimeMillis() / 1000L) + expiresIn;
String expectedScope = null;
response = new FileAccessTokenResponse(accessToken,
tokenType,
expiresIn, refreshToken, idToken,
exp, expectedScope);
long startTimeMillis = response.getStartTimeMilliseconds();
tmpFile = File.createTempFile("access_token", ".json");
tmpFile.deleteOnExit();
| // Path: here-oauth-client/src/main/java/com/here/account/util/JacksonSerializer.java
// public class JacksonSerializer implements Serializer {
//
// public JacksonSerializer() {
// }
//
// /**
// * {@inheritDoc}
// */
// public Map<String, Object> jsonToMap(InputStream jsonInputStream) {
// try {
// return JsonSerializer.toMap(jsonInputStream);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public <T> T jsonToPojo(InputStream jsonInputStream, Class<T> pojoClass) {
// try {
// return JsonSerializer.toPojo(jsonInputStream, pojoClass);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public String objectToJson(Object object) {
// try {
// return JsonSerializer.objectToJson(object);
// } catch (JsonProcessingException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
// @Override
// public void writeObjectToJson(OutputStream outputStream, Object object) {
// try {
// JsonSerializer.writeObjectToJson(outputStream, object);
// } catch (IOException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Serializer.java
// public interface Serializer {
//
// /**
// * Reads from the input jsonInputStream containing bytes from a JSON stream,
// * and returns the corresponding Map<String, Object>.
// *
// * @param jsonInputStream the input stream
// * @return the corresponding deserialized Map<String, Object>
// */
// Map<String, Object> jsonToMap(InputStream jsonInputStream);
//
// <T> T jsonToPojo (InputStream jsonInputStream, Class<T> pojoClass);
//
// String objectToJson(Object object);
//
// void writeObjectToJson(OutputStream outputStream, Object object);
//
// }
// Path: here-oauth-client/src/test/java/com/here/account/oauth2/FileAccessTokenResponseTest.java
import static org.junit.Assert.assertTrue;
import com.here.account.util.JacksonSerializer;
import com.here.account.util.Serializer;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Tests the timestamp and relative timings for a FileAccessTokenResponse,
* when read multiple times from the same previously-serialized file,
* over increasing clock time.
*
* @throws IOException if IO trouble
* @throws InterruptedException if interrupted during sleep
*/
@Test
public void test_timings_sameFile_multipleReads() throws IOException, InterruptedException {
String accessToken = "my-access-token";
String tokenType = "bearer";
Long expiresIn = 45L;
String refreshToken = null;
String idToken = null;
Long exp = (System.currentTimeMillis() / 1000L) + expiresIn;
String expectedScope = null;
response = new FileAccessTokenResponse(accessToken,
tokenType,
expiresIn, refreshToken, idToken,
exp, expectedScope);
long startTimeMillis = response.getStartTimeMilliseconds();
tmpFile = File.createTempFile("access_token", ".json");
tmpFile.deleteOnExit();
| serializer = new JacksonSerializer(); |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/util/RefreshableResponseProviderTest.java | // Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ExpiringResponse {
//
// /**
// * Seconds until expiration, at time of receipt of this object.
// *
// * @return the seconds until expiration
// */
// Long getExpiresIn();
//
// /**
// * Current time milliseconds UTC at the time of construction of this object.
// * In practice, this can generally be considered to be close to the time of receipt of
// * the object from the server.
// *
// * @return the start time in milliseconds UTC when this object was received.
// */
// Long getStartTimeMilliseconds();
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ResponseRefresher<T extends ExpiringResponse> {
//
// /**
// * Invoked when on a specified interval to refresh the token.
// *
// * @param previous the previous token. Make sure your implementation
// * can handle the initial case where previous is null.
// * @return a new token
// */
// T refresh(T previous);
// }
| import com.here.account.util.RefreshableResponseProvider.ExpiringResponse;
import com.here.account.util.RefreshableResponseProvider.ResponseRefresher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import java.util.concurrent.ScheduledExecutorService;
import static org.junit.Assert.assertTrue; | package com.here.account.util;
public class RefreshableResponseProviderTest {
RefreshableResponseProvider<MyExpiringResponse> refreshableResponseProvider;
| // Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ExpiringResponse {
//
// /**
// * Seconds until expiration, at time of receipt of this object.
// *
// * @return the seconds until expiration
// */
// Long getExpiresIn();
//
// /**
// * Current time milliseconds UTC at the time of construction of this object.
// * In practice, this can generally be considered to be close to the time of receipt of
// * the object from the server.
// *
// * @return the start time in milliseconds UTC when this object was received.
// */
// Long getStartTimeMilliseconds();
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ResponseRefresher<T extends ExpiringResponse> {
//
// /**
// * Invoked when on a specified interval to refresh the token.
// *
// * @param previous the previous token. Make sure your implementation
// * can handle the initial case where previous is null.
// * @return a new token
// */
// T refresh(T previous);
// }
// Path: here-oauth-client/src/test/java/com/here/account/util/RefreshableResponseProviderTest.java
import com.here.account.util.RefreshableResponseProvider.ExpiringResponse;
import com.here.account.util.RefreshableResponseProvider.ResponseRefresher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import java.util.concurrent.ScheduledExecutorService;
import static org.junit.Assert.assertTrue;
package com.here.account.util;
public class RefreshableResponseProviderTest {
RefreshableResponseProvider<MyExpiringResponse> refreshableResponseProvider;
| public class MyExpiringResponse implements ExpiringResponse { |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/util/RefreshableResponseProviderTest.java | // Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ExpiringResponse {
//
// /**
// * Seconds until expiration, at time of receipt of this object.
// *
// * @return the seconds until expiration
// */
// Long getExpiresIn();
//
// /**
// * Current time milliseconds UTC at the time of construction of this object.
// * In practice, this can generally be considered to be close to the time of receipt of
// * the object from the server.
// *
// * @return the start time in milliseconds UTC when this object was received.
// */
// Long getStartTimeMilliseconds();
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ResponseRefresher<T extends ExpiringResponse> {
//
// /**
// * Invoked when on a specified interval to refresh the token.
// *
// * @param previous the previous token. Make sure your implementation
// * can handle the initial case where previous is null.
// * @return a new token
// */
// T refresh(T previous);
// }
| import com.here.account.util.RefreshableResponseProvider.ExpiringResponse;
import com.here.account.util.RefreshableResponseProvider.ResponseRefresher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import java.util.concurrent.ScheduledExecutorService;
import static org.junit.Assert.assertTrue; | package com.here.account.util;
public class RefreshableResponseProviderTest {
RefreshableResponseProvider<MyExpiringResponse> refreshableResponseProvider;
public class MyExpiringResponse implements ExpiringResponse {
private long startTimeMillis;
public MyExpiringResponse() {
this.startTimeMillis = System.currentTimeMillis();
}
/**
* {@inheritDoc}
*/
@Override
public Long getExpiresIn() {
// 10 minutes
return 10*60L;
}
/**
* {@inheritDoc}
*/
@Override
public Long getStartTimeMilliseconds() {
return startTimeMillis;
}
}
Long refreshIntervalMillis;
MyExpiringResponse initialToken; | // Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ExpiringResponse {
//
// /**
// * Seconds until expiration, at time of receipt of this object.
// *
// * @return the seconds until expiration
// */
// Long getExpiresIn();
//
// /**
// * Current time milliseconds UTC at the time of construction of this object.
// * In practice, this can generally be considered to be close to the time of receipt of
// * the object from the server.
// *
// * @return the start time in milliseconds UTC when this object was received.
// */
// Long getStartTimeMilliseconds();
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/RefreshableResponseProvider.java
// public interface ResponseRefresher<T extends ExpiringResponse> {
//
// /**
// * Invoked when on a specified interval to refresh the token.
// *
// * @param previous the previous token. Make sure your implementation
// * can handle the initial case where previous is null.
// * @return a new token
// */
// T refresh(T previous);
// }
// Path: here-oauth-client/src/test/java/com/here/account/util/RefreshableResponseProviderTest.java
import com.here.account.util.RefreshableResponseProvider.ExpiringResponse;
import com.here.account.util.RefreshableResponseProvider.ResponseRefresher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import java.util.concurrent.ScheduledExecutorService;
import static org.junit.Assert.assertTrue;
package com.here.account.util;
public class RefreshableResponseProviderTest {
RefreshableResponseProvider<MyExpiringResponse> refreshableResponseProvider;
public class MyExpiringResponse implements ExpiringResponse {
private long startTimeMillis;
public MyExpiringResponse() {
this.startTimeMillis = System.currentTimeMillis();
}
/**
* {@inheritDoc}
*/
@Override
public Long getExpiresIn() {
// 10 minutes
return 10*60L;
}
/**
* {@inheritDoc}
*/
@Override
public Long getStartTimeMilliseconds() {
return startTimeMillis;
}
}
Long refreshIntervalMillis;
MyExpiringResponse initialToken; | ResponseRefresher<MyExpiringResponse> refreshTokenFunction; |
heremaps/here-aaa-java-sdk | here-oauth-client/src/main/java/com/here/account/oauth2/retry/Retryable.java | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public interface HttpProvider extends Closeable {
//
// /**
// * Wrapper for an HTTP request.
// */
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// /**
// * Wrapper for authorizing HTTP requests.
// */
// public static interface HttpRequestAuthorizer {
//
// /**
// * Computes and adds a signature or token to the request as appropriate
// * for the authentication or authorization scheme.
// *
// * @param httpRequest the HttpRequest under construction,
// * to which to attach authorization
// * @param method the HTTP method
// * @param url the URL of the request
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// */
// void authorize(HttpRequest httpRequest, String method, String url,
// Map<String, List<String>> formParams);
//
// }
//
// /**
// * Wrapper for HTTP responses.
// */
// public static interface HttpResponse {
//
// /**
// * Returns the HTTP response status code.
// *
// * @return the HTTP response status code as an int
// */
// int getStatusCode();
//
// /**
// * Returns the HTTP Content-Length header value.
// * The content length of the response body.
// *
// * @return the content length of the response body.
// */
// long getContentLength();
//
// /**
// * Get the response body, as an <tt>InputStream</tt>.
// *
// * @return if there was a response entity, returns the InputStream reading bytes
// * from that response entity.
// * otherwise, if there was no response entity, this method returns null.
// * @throws IOException if there is I/O trouble
// */
// InputStream getResponseBody() throws IOException;
//
// /**
// * Returns all the headers from the response
// * @return returns a Map of headers if the method implementation returns the headers
// * or throws Unsupported Operation Exception if the method is not implemented
// */
//
// default Map<String, List<String>> getHeaders() {
// throw new UnsupportedOperationException();
// }
//
// }
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and requestBodyJson.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param requestBodyJson the
// * Content-Type: application/json
// * JSON request body.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url, String requestBodyJson);
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and formParams.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url,
// Map<String, List<String>> formParams);
//
// /**
// * Execute the <tt>httpRequest</tt>.
// * Implementing classes would commonly invoke or schedule a RESTful HTTPS API call
// * over the wire to the configured Service as part of <tt>execute</tt>.
// *
// * @param httpRequest the HttpRequest
// * @return the HttpResponse to the request
// * @throws HttpException if there is trouble executing the httpRequest
// * @throws IOException if there is I/O trouble executing the httpRequest
// */
// HttpResponse execute(HttpRequest httpRequest) throws HttpException, IOException;
//
// }
| import com.here.account.http.HttpException;
import com.here.account.http.HttpProvider;
import java.io.IOException; | package com.here.account.oauth2.retry;
/**
* An interface for an operation that can be retried using a {@link RetryExecutor}
*
*/
@FunctionalInterface
public interface Retryable {
/**
* Execute an operation with retry semantics.
* @return http response from retry semantics.
* @throws IOException
* @throws HttpException
*/ | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public interface HttpProvider extends Closeable {
//
// /**
// * Wrapper for an HTTP request.
// */
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// /**
// * Wrapper for authorizing HTTP requests.
// */
// public static interface HttpRequestAuthorizer {
//
// /**
// * Computes and adds a signature or token to the request as appropriate
// * for the authentication or authorization scheme.
// *
// * @param httpRequest the HttpRequest under construction,
// * to which to attach authorization
// * @param method the HTTP method
// * @param url the URL of the request
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// */
// void authorize(HttpRequest httpRequest, String method, String url,
// Map<String, List<String>> formParams);
//
// }
//
// /**
// * Wrapper for HTTP responses.
// */
// public static interface HttpResponse {
//
// /**
// * Returns the HTTP response status code.
// *
// * @return the HTTP response status code as an int
// */
// int getStatusCode();
//
// /**
// * Returns the HTTP Content-Length header value.
// * The content length of the response body.
// *
// * @return the content length of the response body.
// */
// long getContentLength();
//
// /**
// * Get the response body, as an <tt>InputStream</tt>.
// *
// * @return if there was a response entity, returns the InputStream reading bytes
// * from that response entity.
// * otherwise, if there was no response entity, this method returns null.
// * @throws IOException if there is I/O trouble
// */
// InputStream getResponseBody() throws IOException;
//
// /**
// * Returns all the headers from the response
// * @return returns a Map of headers if the method implementation returns the headers
// * or throws Unsupported Operation Exception if the method is not implemented
// */
//
// default Map<String, List<String>> getHeaders() {
// throw new UnsupportedOperationException();
// }
//
// }
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and requestBodyJson.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param requestBodyJson the
// * Content-Type: application/json
// * JSON request body.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url, String requestBodyJson);
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and formParams.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url,
// Map<String, List<String>> formParams);
//
// /**
// * Execute the <tt>httpRequest</tt>.
// * Implementing classes would commonly invoke or schedule a RESTful HTTPS API call
// * over the wire to the configured Service as part of <tt>execute</tt>.
// *
// * @param httpRequest the HttpRequest
// * @return the HttpResponse to the request
// * @throws HttpException if there is trouble executing the httpRequest
// * @throws IOException if there is I/O trouble executing the httpRequest
// */
// HttpResponse execute(HttpRequest httpRequest) throws HttpException, IOException;
//
// }
// Path: here-oauth-client/src/main/java/com/here/account/oauth2/retry/Retryable.java
import com.here.account.http.HttpException;
import com.here.account.http.HttpProvider;
import java.io.IOException;
package com.here.account.oauth2.retry;
/**
* An interface for an operation that can be retried using a {@link RetryExecutor}
*
*/
@FunctionalInterface
public interface Retryable {
/**
* Execute an operation with retry semantics.
* @return http response from retry semantics.
* @throws IOException
* @throws HttpException
*/ | HttpProvider.HttpResponse execute() throws IOException, HttpException; |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/auth/OAuth1SignerTest.java | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Clock.java
// public interface Clock {
//
// /**
// * java.lang.System Clock (digital approximation of wall clock).
// */
// Clock SYSTEM = new Clock() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public long currentTimeMillis() {
// return System.currentTimeMillis();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// ) {
// scheduledExecutorService.schedule(
// runnable,
// millisecondsInTheFutureToSchedule,
// TimeUnit.MILLISECONDS
// );
//
// }
// };
//
// /**
// * Returns the milliseconds UTC since the epoch.
// *
// * @return this clock's currentTimeMillis in UTC since the epoch.
// */
// long currentTimeMillis();
//
// /**
// * Schedules <tt>runnable</tt> the specified <tt>millisecondsInTheFutureToSchedule</tt>
// * using <tt>scheduledExecutorService</tt>.
// *
// * @param scheduledExecutorService the ScheduledExecutorService to submit the runnable to
// * @param runnable the runnable to execute on a schedule
// * @param millisecondsInTheFutureToSchedule the schedule of milliseconds in the future,
// * approximating when the runnable should run.
// */
// void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// );
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
| import org.junit.Before;
import org.junit.Test;
import com.here.account.http.HttpProvider.HttpRequest;
import com.here.account.util.Clock;
import com.here.account.util.OAuthConstants;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec; | /*
* Copyright (c) 2016 HERE Europe B.V.
*
* 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.here.account.auth;
public class OAuth1SignerTest {
private String accessKeyId = "access-key-id";
private String accessKeySecret = "access-key-secret";
private OAuth1Signer oauth1Signer;
MyHttpRequest httpRequest;
| // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Clock.java
// public interface Clock {
//
// /**
// * java.lang.System Clock (digital approximation of wall clock).
// */
// Clock SYSTEM = new Clock() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public long currentTimeMillis() {
// return System.currentTimeMillis();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// ) {
// scheduledExecutorService.schedule(
// runnable,
// millisecondsInTheFutureToSchedule,
// TimeUnit.MILLISECONDS
// );
//
// }
// };
//
// /**
// * Returns the milliseconds UTC since the epoch.
// *
// * @return this clock's currentTimeMillis in UTC since the epoch.
// */
// long currentTimeMillis();
//
// /**
// * Schedules <tt>runnable</tt> the specified <tt>millisecondsInTheFutureToSchedule</tt>
// * using <tt>scheduledExecutorService</tt>.
// *
// * @param scheduledExecutorService the ScheduledExecutorService to submit the runnable to
// * @param runnable the runnable to execute on a schedule
// * @param millisecondsInTheFutureToSchedule the schedule of milliseconds in the future,
// * approximating when the runnable should run.
// */
// void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// );
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
// Path: here-oauth-client/src/test/java/com/here/account/auth/OAuth1SignerTest.java
import org.junit.Before;
import org.junit.Test;
import com.here.account.http.HttpProvider.HttpRequest;
import com.here.account.util.Clock;
import com.here.account.util.OAuthConstants;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/*
* Copyright (c) 2016 HERE Europe B.V.
*
* 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.here.account.auth;
public class OAuth1SignerTest {
private String accessKeyId = "access-key-id";
private String accessKeySecret = "access-key-secret";
private OAuth1Signer oauth1Signer;
MyHttpRequest httpRequest;
| private static class MyHttpRequest implements HttpRequest { |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/auth/OAuth1SignerTest.java | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Clock.java
// public interface Clock {
//
// /**
// * java.lang.System Clock (digital approximation of wall clock).
// */
// Clock SYSTEM = new Clock() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public long currentTimeMillis() {
// return System.currentTimeMillis();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// ) {
// scheduledExecutorService.schedule(
// runnable,
// millisecondsInTheFutureToSchedule,
// TimeUnit.MILLISECONDS
// );
//
// }
// };
//
// /**
// * Returns the milliseconds UTC since the epoch.
// *
// * @return this clock's currentTimeMillis in UTC since the epoch.
// */
// long currentTimeMillis();
//
// /**
// * Schedules <tt>runnable</tt> the specified <tt>millisecondsInTheFutureToSchedule</tt>
// * using <tt>scheduledExecutorService</tt>.
// *
// * @param scheduledExecutorService the ScheduledExecutorService to submit the runnable to
// * @param runnable the runnable to execute on a schedule
// * @param millisecondsInTheFutureToSchedule the schedule of milliseconds in the future,
// * approximating when the runnable should run.
// */
// void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// );
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
| import org.junit.Before;
import org.junit.Test;
import com.here.account.http.HttpProvider.HttpRequest;
import com.here.account.util.Clock;
import com.here.account.util.OAuthConstants;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec; | /*
* Copyright (c) 2016 HERE Europe B.V.
*
* 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.here.account.auth;
public class OAuth1SignerTest {
private String accessKeyId = "access-key-id";
private String accessKeySecret = "access-key-secret";
private OAuth1Signer oauth1Signer;
MyHttpRequest httpRequest;
private static class MyHttpRequest implements HttpRequest {
private String authorizationHeader;
public MyHttpRequest() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public void addAuthorizationHeader(String value) {
this.authorizationHeader = value;
}
@Override
public void addHeader(String name, String value) {
// no-op
}
public String getAuthorizationHeader() {
return this.authorizationHeader;
}
}
private String method;
private String url; | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Clock.java
// public interface Clock {
//
// /**
// * java.lang.System Clock (digital approximation of wall clock).
// */
// Clock SYSTEM = new Clock() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public long currentTimeMillis() {
// return System.currentTimeMillis();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// ) {
// scheduledExecutorService.schedule(
// runnable,
// millisecondsInTheFutureToSchedule,
// TimeUnit.MILLISECONDS
// );
//
// }
// };
//
// /**
// * Returns the milliseconds UTC since the epoch.
// *
// * @return this clock's currentTimeMillis in UTC since the epoch.
// */
// long currentTimeMillis();
//
// /**
// * Schedules <tt>runnable</tt> the specified <tt>millisecondsInTheFutureToSchedule</tt>
// * using <tt>scheduledExecutorService</tt>.
// *
// * @param scheduledExecutorService the ScheduledExecutorService to submit the runnable to
// * @param runnable the runnable to execute on a schedule
// * @param millisecondsInTheFutureToSchedule the schedule of milliseconds in the future,
// * approximating when the runnable should run.
// */
// void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// );
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
// Path: here-oauth-client/src/test/java/com/here/account/auth/OAuth1SignerTest.java
import org.junit.Before;
import org.junit.Test;
import com.here.account.http.HttpProvider.HttpRequest;
import com.here.account.util.Clock;
import com.here.account.util.OAuthConstants;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/*
* Copyright (c) 2016 HERE Europe B.V.
*
* 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.here.account.auth;
public class OAuth1SignerTest {
private String accessKeyId = "access-key-id";
private String accessKeySecret = "access-key-secret";
private OAuth1Signer oauth1Signer;
MyHttpRequest httpRequest;
private static class MyHttpRequest implements HttpRequest {
private String authorizationHeader;
public MyHttpRequest() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public void addAuthorizationHeader(String value) {
this.authorizationHeader = value;
}
@Override
public void addHeader(String name, String value) {
// no-op
}
public String getAuthorizationHeader() {
return this.authorizationHeader;
}
}
private String method;
private String url; | private Clock clock; |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/auth/OAuth1SignerTest.java | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Clock.java
// public interface Clock {
//
// /**
// * java.lang.System Clock (digital approximation of wall clock).
// */
// Clock SYSTEM = new Clock() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public long currentTimeMillis() {
// return System.currentTimeMillis();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// ) {
// scheduledExecutorService.schedule(
// runnable,
// millisecondsInTheFutureToSchedule,
// TimeUnit.MILLISECONDS
// );
//
// }
// };
//
// /**
// * Returns the milliseconds UTC since the epoch.
// *
// * @return this clock's currentTimeMillis in UTC since the epoch.
// */
// long currentTimeMillis();
//
// /**
// * Schedules <tt>runnable</tt> the specified <tt>millisecondsInTheFutureToSchedule</tt>
// * using <tt>scheduledExecutorService</tt>.
// *
// * @param scheduledExecutorService the ScheduledExecutorService to submit the runnable to
// * @param runnable the runnable to execute on a schedule
// * @param millisecondsInTheFutureToSchedule the schedule of milliseconds in the future,
// * approximating when the runnable should run.
// */
// void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// );
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
| import org.junit.Before;
import org.junit.Test;
import com.here.account.http.HttpProvider.HttpRequest;
import com.here.account.util.Clock;
import com.here.account.util.OAuthConstants;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec; | String shaVariant = "SHA256";//"SHA1";
String requestParameters = "oauth_consumer_key="+accessKeyId+"&oauth_nonce="+nonce+"&oauth_signature_method=HMAC-"+shaVariant+"&oauth_timestamp="+oauth_timestamp+"&oauth_version=1.0";
String signatureBaseString = "GET&"
+urlEncode(url)+"&"
+ urlEncode(requestParameters); // no request parameters in this test case
System.out.println("test signatureBaseString "+signatureBaseString);
String key = urlEncode(accessKeySecret) + "&"; // no token shared-secret
String expectedSignature = HmacSHAN(key, "Hmac"+shaVariant, signatureBaseString);
String expectedSignatureInAuthorizationHeader = urlEncode(expectedSignature);
oauth1Signer.authorize(httpRequest, method, url, null);
String actualHeader = httpRequest.getAuthorizationHeader();
Pattern pattern = Pattern.compile("\\A.*oauth_signature=\\\"([^\\\"]+).*\\z");
Matcher matcher = pattern.matcher(actualHeader);
assertTrue("pattern wasn't matched: "+actualHeader, matcher.matches());
String actualSignature = matcher.group(1);
assertTrue("expected signature "+expectedSignatureInAuthorizationHeader+", actual signature "+actualSignature,
expectedSignatureInAuthorizationHeader.equals(actualSignature));
}
private String urlEncode(String s) throws UnsupportedEncodingException { | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/Clock.java
// public interface Clock {
//
// /**
// * java.lang.System Clock (digital approximation of wall clock).
// */
// Clock SYSTEM = new Clock() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public long currentTimeMillis() {
// return System.currentTimeMillis();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// ) {
// scheduledExecutorService.schedule(
// runnable,
// millisecondsInTheFutureToSchedule,
// TimeUnit.MILLISECONDS
// );
//
// }
// };
//
// /**
// * Returns the milliseconds UTC since the epoch.
// *
// * @return this clock's currentTimeMillis in UTC since the epoch.
// */
// long currentTimeMillis();
//
// /**
// * Schedules <tt>runnable</tt> the specified <tt>millisecondsInTheFutureToSchedule</tt>
// * using <tt>scheduledExecutorService</tt>.
// *
// * @param scheduledExecutorService the ScheduledExecutorService to submit the runnable to
// * @param runnable the runnable to execute on a schedule
// * @param millisecondsInTheFutureToSchedule the schedule of milliseconds in the future,
// * approximating when the runnable should run.
// */
// void schedule(ScheduledExecutorService scheduledExecutorService,
// Runnable runnable,
// long millisecondsInTheFutureToSchedule
// );
// }
//
// Path: here-oauth-client/src/main/java/com/here/account/util/OAuthConstants.java
// public class OAuthConstants {
//
// /**
// * We commonly use "UTF-8" charset, this String is its name.
// */
// public static final String UTF_8_STRING = "UTF-8";
//
// /**
// * This is the constant for the "UTF-8" Charset already loaded.
// */
// public static final Charset UTF_8_CHARSET = Charset.forName(UTF_8_STRING);
// }
// Path: here-oauth-client/src/test/java/com/here/account/auth/OAuth1SignerTest.java
import org.junit.Before;
import org.junit.Test;
import com.here.account.http.HttpProvider.HttpRequest;
import com.here.account.util.Clock;
import com.here.account.util.OAuthConstants;
import static org.junit.Assert.assertTrue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
String shaVariant = "SHA256";//"SHA1";
String requestParameters = "oauth_consumer_key="+accessKeyId+"&oauth_nonce="+nonce+"&oauth_signature_method=HMAC-"+shaVariant+"&oauth_timestamp="+oauth_timestamp+"&oauth_version=1.0";
String signatureBaseString = "GET&"
+urlEncode(url)+"&"
+ urlEncode(requestParameters); // no request parameters in this test case
System.out.println("test signatureBaseString "+signatureBaseString);
String key = urlEncode(accessKeySecret) + "&"; // no token shared-secret
String expectedSignature = HmacSHAN(key, "Hmac"+shaVariant, signatureBaseString);
String expectedSignatureInAuthorizationHeader = urlEncode(expectedSignature);
oauth1Signer.authorize(httpRequest, method, url, null);
String actualHeader = httpRequest.getAuthorizationHeader();
Pattern pattern = Pattern.compile("\\A.*oauth_signature=\\\"([^\\\"]+).*\\z");
Matcher matcher = pattern.matcher(actualHeader);
assertTrue("pattern wasn't matched: "+actualHeader, matcher.matches());
String actualSignature = matcher.group(1);
assertTrue("expected signature "+expectedSignatureInAuthorizationHeader+", actual signature "+actualSignature,
expectedSignatureInAuthorizationHeader.equals(actualSignature));
}
private String urlEncode(String s) throws UnsupportedEncodingException { | return URLEncoder.encode(s, OAuthConstants.UTF_8_STRING).replaceAll("\\+", "%20"); |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/auth/provider/FromHereCredentialsIniFileTest.java | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpConstants.java
// public enum HttpMethods {
// /**
// * See <a href="https://tools.ietf.org/html/rfc7231#section-4.3.1">HTTP/1.1 Semantics and Content: GET</a>.
// */
// GET("GET"),
// POST("POST");
//
// private final String method;
//
// private HttpMethods(String method) {
// this.method = method;
// }
//
// /**
// * Returns the HTTP Method to be sent with the HTTP Request message.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
// }
| import com.here.account.http.HttpConstants.HttpMethods;
import org.junit.After;
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; |
@Test
public void test_default_file() {
fromFile = new FromHereCredentialsIniFile();
File actualFile = fromFile.getFile();
String actualName = actualFile.getName();
String expectedName = "credentials.ini";
assertTrue("default file name expected "+expectedName+", actual "+actualName, expectedName.equals(actualName));
}
@Test
public void test_basic_file() throws IOException {
createTmpFile();
FromHereCredentialsIniStreamTest otherTezt = new FromHereCredentialsIniStreamTest();
byte[] bytes = otherTezt.getDefaultIniStreamContents(false);
try (OutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(bytes);
outputStream.flush();
}
// use the file
fromFile = new FromHereCredentialsIniFile(file, TEST_DEFAULT_INI_SECTION_NAME);
otherTezt.verifyExpected(fromFile);
}
@Test
public void test_getHttpMethod() {
fromFile = new FromHereCredentialsIniFile(); | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpConstants.java
// public enum HttpMethods {
// /**
// * See <a href="https://tools.ietf.org/html/rfc7231#section-4.3.1">HTTP/1.1 Semantics and Content: GET</a>.
// */
// GET("GET"),
// POST("POST");
//
// private final String method;
//
// private HttpMethods(String method) {
// this.method = method;
// }
//
// /**
// * Returns the HTTP Method to be sent with the HTTP Request message.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
// }
// Path: here-oauth-client/src/test/java/com/here/account/auth/provider/FromHereCredentialsIniFileTest.java
import com.here.account.http.HttpConstants.HttpMethods;
import org.junit.After;
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@Test
public void test_default_file() {
fromFile = new FromHereCredentialsIniFile();
File actualFile = fromFile.getFile();
String actualName = actualFile.getName();
String expectedName = "credentials.ini";
assertTrue("default file name expected "+expectedName+", actual "+actualName, expectedName.equals(actualName));
}
@Test
public void test_basic_file() throws IOException {
createTmpFile();
FromHereCredentialsIniStreamTest otherTezt = new FromHereCredentialsIniStreamTest();
byte[] bytes = otherTezt.getDefaultIniStreamContents(false);
try (OutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(bytes);
outputStream.flush();
}
// use the file
fromFile = new FromHereCredentialsIniFile(file, TEST_DEFAULT_INI_SECTION_NAME);
otherTezt.verifyExpected(fromFile);
}
@Test
public void test_getHttpMethod() {
fromFile = new FromHereCredentialsIniFile(); | HttpMethods httpMethod = fromFile.getHttpMethod(); |
heremaps/here-aaa-java-sdk | here-oauth-client/src/main/java/com/here/account/oauth2/retry/RetryContext.java | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public interface HttpProvider extends Closeable {
//
// /**
// * Wrapper for an HTTP request.
// */
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// /**
// * Wrapper for authorizing HTTP requests.
// */
// public static interface HttpRequestAuthorizer {
//
// /**
// * Computes and adds a signature or token to the request as appropriate
// * for the authentication or authorization scheme.
// *
// * @param httpRequest the HttpRequest under construction,
// * to which to attach authorization
// * @param method the HTTP method
// * @param url the URL of the request
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// */
// void authorize(HttpRequest httpRequest, String method, String url,
// Map<String, List<String>> formParams);
//
// }
//
// /**
// * Wrapper for HTTP responses.
// */
// public static interface HttpResponse {
//
// /**
// * Returns the HTTP response status code.
// *
// * @return the HTTP response status code as an int
// */
// int getStatusCode();
//
// /**
// * Returns the HTTP Content-Length header value.
// * The content length of the response body.
// *
// * @return the content length of the response body.
// */
// long getContentLength();
//
// /**
// * Get the response body, as an <tt>InputStream</tt>.
// *
// * @return if there was a response entity, returns the InputStream reading bytes
// * from that response entity.
// * otherwise, if there was no response entity, this method returns null.
// * @throws IOException if there is I/O trouble
// */
// InputStream getResponseBody() throws IOException;
//
// /**
// * Returns all the headers from the response
// * @return returns a Map of headers if the method implementation returns the headers
// * or throws Unsupported Operation Exception if the method is not implemented
// */
//
// default Map<String, List<String>> getHeaders() {
// throw new UnsupportedOperationException();
// }
//
// }
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and requestBodyJson.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param requestBodyJson the
// * Content-Type: application/json
// * JSON request body.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url, String requestBodyJson);
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and formParams.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url,
// Map<String, List<String>> formParams);
//
// /**
// * Execute the <tt>httpRequest</tt>.
// * Implementing classes would commonly invoke or schedule a RESTful HTTPS API call
// * over the wire to the configured Service as part of <tt>execute</tt>.
// *
// * @param httpRequest the HttpRequest
// * @return the HttpResponse to the request
// * @throws HttpException if there is trouble executing the httpRequest
// * @throws IOException if there is I/O trouble executing the httpRequest
// */
// HttpResponse execute(HttpRequest httpRequest) throws HttpException, IOException;
//
// }
| import com.here.account.http.HttpProvider; | package com.here.account.oauth2.retry;
/**
* A {@link RetryContext} contains data set to be used for next retry.
*/
public class RetryContext {
private int retryCount; | // Path: here-oauth-client/src/main/java/com/here/account/http/HttpProvider.java
// public interface HttpProvider extends Closeable {
//
// /**
// * Wrapper for an HTTP request.
// */
// public static interface HttpRequest {
//
// /**
// * Add the Authorization header to this request, with the specified
// * <tt>value</tt>.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7235#section-4.2">RFC 7235</a>.
// *
// * @param value the value to add in the Authorization header
// */
// void addAuthorizationHeader(String value);
//
// /**
// * Adds the additional (name, value)-pair to be sent as HTTP Headers
// * on the HTTP Request.
// * See also
// * <a href="https://tools.ietf.org/html/rfc7230#section-3.2">RFC 7230</a>.
// *
// * @param name the name of the HTTP Header to add
// * @param value the value of the HTTP Header to add
// */
// default void addHeader(String name, String value) {
// throw new UnsupportedOperationException("addHeader not supported");
// }
//
// }
//
// /**
// * Wrapper for authorizing HTTP requests.
// */
// public static interface HttpRequestAuthorizer {
//
// /**
// * Computes and adds a signature or token to the request as appropriate
// * for the authentication or authorization scheme.
// *
// * @param httpRequest the HttpRequest under construction,
// * to which to attach authorization
// * @param method the HTTP method
// * @param url the URL of the request
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// */
// void authorize(HttpRequest httpRequest, String method, String url,
// Map<String, List<String>> formParams);
//
// }
//
// /**
// * Wrapper for HTTP responses.
// */
// public static interface HttpResponse {
//
// /**
// * Returns the HTTP response status code.
// *
// * @return the HTTP response status code as an int
// */
// int getStatusCode();
//
// /**
// * Returns the HTTP Content-Length header value.
// * The content length of the response body.
// *
// * @return the content length of the response body.
// */
// long getContentLength();
//
// /**
// * Get the response body, as an <tt>InputStream</tt>.
// *
// * @return if there was a response entity, returns the InputStream reading bytes
// * from that response entity.
// * otherwise, if there was no response entity, this method returns null.
// * @throws IOException if there is I/O trouble
// */
// InputStream getResponseBody() throws IOException;
//
// /**
// * Returns all the headers from the response
// * @return returns a Map of headers if the method implementation returns the headers
// * or throws Unsupported Operation Exception if the method is not implemented
// */
//
// default Map<String, List<String>> getHeaders() {
// throw new UnsupportedOperationException();
// }
//
// }
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and requestBodyJson.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param requestBodyJson the
// * Content-Type: application/json
// * JSON request body.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url, String requestBodyJson);
//
// /**
// * Gets the RequestBuilder, with the specified method, url, and formParams.
// * The Authorization header has already been set according to the
// * httpRequestAuthorizer implementation.
// *
// * @param httpRequestAuthorizer for adding the Authorization header value
// * @param method HTTP method value
// * @param url HTTP request URL
// * @param formParams the
// * Content-Type: application/x-www-form-urlencoded
// * form parameters.
// * @return the HttpRequest object you can {@link #execute(HttpRequest)}.
// */
// HttpRequest getRequest(HttpRequestAuthorizer httpRequestAuthorizer, String method, String url,
// Map<String, List<String>> formParams);
//
// /**
// * Execute the <tt>httpRequest</tt>.
// * Implementing classes would commonly invoke or schedule a RESTful HTTPS API call
// * over the wire to the configured Service as part of <tt>execute</tt>.
// *
// * @param httpRequest the HttpRequest
// * @return the HttpResponse to the request
// * @throws HttpException if there is trouble executing the httpRequest
// * @throws IOException if there is I/O trouble executing the httpRequest
// */
// HttpResponse execute(HttpRequest httpRequest) throws HttpException, IOException;
//
// }
// Path: here-oauth-client/src/main/java/com/here/account/oauth2/retry/RetryContext.java
import com.here.account.http.HttpProvider;
package com.here.account.oauth2.retry;
/**
* A {@link RetryContext} contains data set to be used for next retry.
*/
public class RetryContext {
private int retryCount; | private HttpProvider.HttpResponse lastRetryResponse; |
heremaps/here-aaa-java-sdk | here-oauth-client/src/test/java/com/here/account/oauth2/AuthorizationRequestTest.java | // Path: here-oauth-client/src/main/java/com/here/account/util/JacksonSerializer.java
// public class JacksonSerializer implements Serializer {
//
// public JacksonSerializer() {
// }
//
// /**
// * {@inheritDoc}
// */
// public Map<String, Object> jsonToMap(InputStream jsonInputStream) {
// try {
// return JsonSerializer.toMap(jsonInputStream);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public <T> T jsonToPojo(InputStream jsonInputStream, Class<T> pojoClass) {
// try {
// return JsonSerializer.toPojo(jsonInputStream, pojoClass);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public String objectToJson(Object object) {
// try {
// return JsonSerializer.objectToJson(object);
// } catch (JsonProcessingException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
// @Override
// public void writeObjectToJson(OutputStream outputStream, Object object) {
// try {
// JsonSerializer.writeObjectToJson(outputStream, object);
// } catch (IOException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
//
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.here.account.util.JacksonSerializer;
import org.junit.Before;
import org.junit.Test;
import org.junit.internal.runners.statements.Fail;
import static org.junit.Assert.*; | }
@Test
public void addFormParam() {
Map<String, List<String>> formParams = new HashMap<String, List<String>>();
String name = "name";
Object value = "value";
authorizationRequest.addFormParam(formParams, name, value);
int size = formParams.size();
int expectedSize = 1;
assertTrue("formParams size was expected "+expectedSize+", actual "+size, size == expectedSize);
List<String> valueList = formParams.get(name);
size = valueList.size();
assertTrue("valueList size was expected "+expectedSize+", actual "+size, size == expectedSize);
String firstValue = valueList.get(0);
assertTrue("firstValue was expected "+value+", actual "+firstValue, value.equals(firstValue));
}
@Test
public void test_request_body() {
Long expiresIn = 123456789L;
String scope = "testScope";
String correlationId = "corrId_abc123";
Map<String, String> additionalHeaders = new HashMap<String, String>();
additionalHeaders.put("testKey", "testValue");
| // Path: here-oauth-client/src/main/java/com/here/account/util/JacksonSerializer.java
// public class JacksonSerializer implements Serializer {
//
// public JacksonSerializer() {
// }
//
// /**
// * {@inheritDoc}
// */
// public Map<String, Object> jsonToMap(InputStream jsonInputStream) {
// try {
// return JsonSerializer.toMap(jsonInputStream);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public <T> T jsonToPojo(InputStream jsonInputStream, Class<T> pojoClass) {
// try {
// return JsonSerializer.toPojo(jsonInputStream, pojoClass);
// } catch (IOException e) {
// throw new RuntimeException("trouble deserializing json: " + e, e);
// }
// }
//
// @Override
// public String objectToJson(Object object) {
// try {
// return JsonSerializer.objectToJson(object);
// } catch (JsonProcessingException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
// @Override
// public void writeObjectToJson(OutputStream outputStream, Object object) {
// try {
// JsonSerializer.writeObjectToJson(outputStream, object);
// } catch (IOException e) {
// throw new RuntimeException("trouble serializing json: " + e, e);
// }
// }
//
//
// }
// Path: here-oauth-client/src/test/java/com/here/account/oauth2/AuthorizationRequestTest.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.here.account.util.JacksonSerializer;
import org.junit.Before;
import org.junit.Test;
import org.junit.internal.runners.statements.Fail;
import static org.junit.Assert.*;
}
@Test
public void addFormParam() {
Map<String, List<String>> formParams = new HashMap<String, List<String>>();
String name = "name";
Object value = "value";
authorizationRequest.addFormParam(formParams, name, value);
int size = formParams.size();
int expectedSize = 1;
assertTrue("formParams size was expected "+expectedSize+", actual "+size, size == expectedSize);
List<String> valueList = formParams.get(name);
size = valueList.size();
assertTrue("valueList size was expected "+expectedSize+", actual "+size, size == expectedSize);
String firstValue = valueList.get(0);
assertTrue("firstValue was expected "+value+", actual "+firstValue, value.equals(firstValue));
}
@Test
public void test_request_body() {
Long expiresIn = 123456789L;
String scope = "testScope";
String correlationId = "corrId_abc123";
Map<String, String> additionalHeaders = new HashMap<String, String>();
additionalHeaders.put("testKey", "testValue");
| JacksonSerializer serializer = new JacksonSerializer(); |
omise/omise-java | src/test/java/co/omise/SerializableTest.java | // Path: src/main/java/co/omise/models/Account.java
// public class Account extends Model {
// @JsonProperty("api_version")
// private String apiVersion;
// @JsonProperty("auto_activate_recipients")
// private boolean autoActivateRecipients;
// @JsonProperty("chain_enabled")
// private boolean chainEnabled;
// @JsonProperty("chain_return_uri")
// private String chainReturnUri;
// private String country;
// private String currency;
// private String email;
// private String location;
// @JsonProperty("metadata_export_keys")
// private Map<String, Object> metadataExportKeys;
// @JsonProperty("supported_currencies")
// private List<String> supportedCurrencies;
// @JsonProperty("team")
// private String teamId;
// @JsonProperty("webhook_uri")
// private String webhookUri;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public String getApiVersion() {
// return this.apiVersion;
// }
//
// public void setApiVersion(String apiVersion) {
// this.apiVersion = apiVersion;
// }
//
// public boolean isAutoActivateRecipients() {
// return this.autoActivateRecipients;
// }
//
// public void setAutoActivateRecipients(boolean autoActivateRecipients) {
// this.autoActivateRecipients = autoActivateRecipients;
// }
//
// public boolean isChainEnabled() {
// return this.chainEnabled;
// }
//
// public void setChainEnabled(boolean chainEnabled) {
// this.chainEnabled = chainEnabled;
// }
//
// public String getChainReturnUri() {
// return this.chainReturnUri;
// }
//
// public void setChainReturnUri(String chainReturnUri) {
// this.chainReturnUri = chainReturnUri;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getCurrency() {
// return this.currency;
// }
//
// public void setCurrency(String currency) {
// this.currency = currency;
// }
//
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public Map<String, Object> getMetadataExportKeys() {
// return this.metadataExportKeys;
// }
//
// public void setMetadataExportKeys(Map<String, Object> metadataExportKeys) {
// this.metadataExportKeys = metadataExportKeys;
// }
//
// public List<String> getSupportedCurrencies() {
// return this.supportedCurrencies;
// }
//
// public void setSupportedCurrencies(List<String> supportedCurrencies) {
// this.supportedCurrencies = supportedCurrencies;
// }
//
// public String getTeamId() {
// return this.teamId;
// }
//
// public void setTeamId(String teamId) {
// this.teamId = teamId;
// }
//
// public String getWebhookUri() {
// return this.webhookUri;
// }
//
// public void setWebhookUri(String webhookUri) {
// this.webhookUri = webhookUri;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Account> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "account");
// }
//
// @Override
// protected ResponseType<Account> type() {
// return new ResponseType<>(Account.class);
// }
// }
//
// public static class UpdateRequestBuilder extends RequestBuilder<Account> {
//
// @JsonProperty("chain_enabled")
// private boolean chainEnabled;
// @JsonProperty("chain_return_uri")
// private String chainReturnUri;
// @JsonProperty("metadata_export_keys")
// private Map<String, Object> metadataExportKeys;
// @JsonProperty("webhook_uri")
// private String webhookUri;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// @Override
// protected String method() {
// return PATCH;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "account");
// }
//
// @Override
// protected ResponseType<Account> type() {
// return new ResponseType<>(Account.class);
// }
//
// public UpdateRequestBuilder chainEnabled(boolean chainEnabled) {
// this.chainEnabled = chainEnabled;
// return this;
// }
//
// public UpdateRequestBuilder chainReturnUri(String chainReturnUri) {
// this.chainReturnUri = chainReturnUri;
// return this;
// }
//
// public UpdateRequestBuilder metadataExportKeys(Map<String, Object> metadataExportKeys) {
// this.metadataExportKeys = metadataExportKeys;
// return this;
// }
//
// public UpdateRequestBuilder webhookUri(String webhookUri) {
// this.webhookUri = webhookUri;
// return this;
// }
//
// public UpdateRequestBuilder zeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// return this;
// }
//
// @Override
// protected RequestBody payload() throws IOException {
// return serialize();
// }
// }
// }
| import co.omise.models.Account;
import org.junit.Before;
import org.junit.Test;
import java.io.*; | package co.omise;
public class SerializableTest {
private String filename = "file.ser";
| // Path: src/main/java/co/omise/models/Account.java
// public class Account extends Model {
// @JsonProperty("api_version")
// private String apiVersion;
// @JsonProperty("auto_activate_recipients")
// private boolean autoActivateRecipients;
// @JsonProperty("chain_enabled")
// private boolean chainEnabled;
// @JsonProperty("chain_return_uri")
// private String chainReturnUri;
// private String country;
// private String currency;
// private String email;
// private String location;
// @JsonProperty("metadata_export_keys")
// private Map<String, Object> metadataExportKeys;
// @JsonProperty("supported_currencies")
// private List<String> supportedCurrencies;
// @JsonProperty("team")
// private String teamId;
// @JsonProperty("webhook_uri")
// private String webhookUri;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public String getApiVersion() {
// return this.apiVersion;
// }
//
// public void setApiVersion(String apiVersion) {
// this.apiVersion = apiVersion;
// }
//
// public boolean isAutoActivateRecipients() {
// return this.autoActivateRecipients;
// }
//
// public void setAutoActivateRecipients(boolean autoActivateRecipients) {
// this.autoActivateRecipients = autoActivateRecipients;
// }
//
// public boolean isChainEnabled() {
// return this.chainEnabled;
// }
//
// public void setChainEnabled(boolean chainEnabled) {
// this.chainEnabled = chainEnabled;
// }
//
// public String getChainReturnUri() {
// return this.chainReturnUri;
// }
//
// public void setChainReturnUri(String chainReturnUri) {
// this.chainReturnUri = chainReturnUri;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getCurrency() {
// return this.currency;
// }
//
// public void setCurrency(String currency) {
// this.currency = currency;
// }
//
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public Map<String, Object> getMetadataExportKeys() {
// return this.metadataExportKeys;
// }
//
// public void setMetadataExportKeys(Map<String, Object> metadataExportKeys) {
// this.metadataExportKeys = metadataExportKeys;
// }
//
// public List<String> getSupportedCurrencies() {
// return this.supportedCurrencies;
// }
//
// public void setSupportedCurrencies(List<String> supportedCurrencies) {
// this.supportedCurrencies = supportedCurrencies;
// }
//
// public String getTeamId() {
// return this.teamId;
// }
//
// public void setTeamId(String teamId) {
// this.teamId = teamId;
// }
//
// public String getWebhookUri() {
// return this.webhookUri;
// }
//
// public void setWebhookUri(String webhookUri) {
// this.webhookUri = webhookUri;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Account> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "account");
// }
//
// @Override
// protected ResponseType<Account> type() {
// return new ResponseType<>(Account.class);
// }
// }
//
// public static class UpdateRequestBuilder extends RequestBuilder<Account> {
//
// @JsonProperty("chain_enabled")
// private boolean chainEnabled;
// @JsonProperty("chain_return_uri")
// private String chainReturnUri;
// @JsonProperty("metadata_export_keys")
// private Map<String, Object> metadataExportKeys;
// @JsonProperty("webhook_uri")
// private String webhookUri;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// @Override
// protected String method() {
// return PATCH;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "account");
// }
//
// @Override
// protected ResponseType<Account> type() {
// return new ResponseType<>(Account.class);
// }
//
// public UpdateRequestBuilder chainEnabled(boolean chainEnabled) {
// this.chainEnabled = chainEnabled;
// return this;
// }
//
// public UpdateRequestBuilder chainReturnUri(String chainReturnUri) {
// this.chainReturnUri = chainReturnUri;
// return this;
// }
//
// public UpdateRequestBuilder metadataExportKeys(Map<String, Object> metadataExportKeys) {
// this.metadataExportKeys = metadataExportKeys;
// return this;
// }
//
// public UpdateRequestBuilder webhookUri(String webhookUri) {
// this.webhookUri = webhookUri;
// return this;
// }
//
// public UpdateRequestBuilder zeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// return this;
// }
//
// @Override
// protected RequestBody payload() throws IOException {
// return serialize();
// }
// }
// }
// Path: src/test/java/co/omise/SerializableTest.java
import co.omise.models.Account;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
package co.omise;
public class SerializableTest {
private String filename = "file.ser";
| private Account account; |
omise/omise-java | src/main/java/co/omise/Example.java | // Path: src/main/java/co/omise/requests/Request.java
// public class Request<T extends OmiseObjectBase> {
// private final String method;
// private final HttpUrl path;
// private final String contentType;
// private final RequestBody payload;
// private final ResponseType<T> type;
//
// /**
// * Constructor for a new Request
// *
// * @param method The HTTP method to use
// * @param path The {@link HttpUrl} for the url path of the HTTP request
// * @param contentType The content type of HTTP request
// * @param payload Additional params passed as OkHttp {@link RequestBody} to the HTTP request
// */
// Request(String method, HttpUrl path, String contentType, RequestBody payload, ResponseType<T> type) {
// this.method = method;
// this.path = path;
// this.contentType = contentType;
// this.payload = payload;
// this.type = type;
// }
//
// /**
// * Gets the HTTP method.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
//
// /**
// * Gets url path for the specific API in the request.
// *
// * @return the url path as {@link HttpUrl}
// */
// public HttpUrl getPath() {
// return path;
// }
//
// /**
// * Gets HTTP request content type.
// *
// * @return the content type as a String
// */
// public String getContentType() {
// return contentType;
// }
//
// /**
// * Gets payload (request params).
// *
// * @return the payload as a {@link RequestBody}
// */
// public RequestBody getPayload() {
// return payload;
// }
//
// public ResponseType<T> getType() {
// return type;
// }
// }
| import co.omise.models.*;
import co.omise.models.schedules.*;
import co.omise.requests.Request;
import org.joda.time.LocalDate;
import java.io.IOException; | package co.omise;
final class Example {
private static final String OMISE_SKEY = "skey_test_123";
void retrieveAccount() throws IOException, OmiseException, ClientException { | // Path: src/main/java/co/omise/requests/Request.java
// public class Request<T extends OmiseObjectBase> {
// private final String method;
// private final HttpUrl path;
// private final String contentType;
// private final RequestBody payload;
// private final ResponseType<T> type;
//
// /**
// * Constructor for a new Request
// *
// * @param method The HTTP method to use
// * @param path The {@link HttpUrl} for the url path of the HTTP request
// * @param contentType The content type of HTTP request
// * @param payload Additional params passed as OkHttp {@link RequestBody} to the HTTP request
// */
// Request(String method, HttpUrl path, String contentType, RequestBody payload, ResponseType<T> type) {
// this.method = method;
// this.path = path;
// this.contentType = contentType;
// this.payload = payload;
// this.type = type;
// }
//
// /**
// * Gets the HTTP method.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
//
// /**
// * Gets url path for the specific API in the request.
// *
// * @return the url path as {@link HttpUrl}
// */
// public HttpUrl getPath() {
// return path;
// }
//
// /**
// * Gets HTTP request content type.
// *
// * @return the content type as a String
// */
// public String getContentType() {
// return contentType;
// }
//
// /**
// * Gets payload (request params).
// *
// * @return the payload as a {@link RequestBody}
// */
// public RequestBody getPayload() {
// return payload;
// }
//
// public ResponseType<T> getType() {
// return type;
// }
// }
// Path: src/main/java/co/omise/Example.java
import co.omise.models.*;
import co.omise.models.schedules.*;
import co.omise.requests.Request;
import org.joda.time.LocalDate;
import java.io.IOException;
package co.omise;
final class Example {
private static final String OMISE_SKEY = "skey_test_123";
void retrieveAccount() throws IOException, OmiseException, ClientException { | Request<Account> getAccountRequest = new Account.GetRequestBuilder().build(); |
omise/omise-java | src/test/java/co/omise/live/LiveForexRequestTest.java | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/requests/Request.java
// public class Request<T extends OmiseObjectBase> {
// private final String method;
// private final HttpUrl path;
// private final String contentType;
// private final RequestBody payload;
// private final ResponseType<T> type;
//
// /**
// * Constructor for a new Request
// *
// * @param method The HTTP method to use
// * @param path The {@link HttpUrl} for the url path of the HTTP request
// * @param contentType The content type of HTTP request
// * @param payload Additional params passed as OkHttp {@link RequestBody} to the HTTP request
// */
// Request(String method, HttpUrl path, String contentType, RequestBody payload, ResponseType<T> type) {
// this.method = method;
// this.path = path;
// this.contentType = contentType;
// this.payload = payload;
// this.type = type;
// }
//
// /**
// * Gets the HTTP method.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
//
// /**
// * Gets url path for the specific API in the request.
// *
// * @return the url path as {@link HttpUrl}
// */
// public HttpUrl getPath() {
// return path;
// }
//
// /**
// * Gets HTTP request content type.
// *
// * @return the content type as a String
// */
// public String getContentType() {
// return contentType;
// }
//
// /**
// * Gets payload (request params).
// *
// * @return the payload as a {@link RequestBody}
// */
// public RequestBody getPayload() {
// return payload;
// }
//
// public ResponseType<T> getType() {
// return type;
// }
// }
| import co.omise.models.Forex;
import co.omise.requests.Request;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*; | package co.omise.live;
public class LiveForexRequestTest extends BaseLiveTest {
@Test
@Ignore("only hit when test on live.")
public void TestGetForex() throws Exception { | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/requests/Request.java
// public class Request<T extends OmiseObjectBase> {
// private final String method;
// private final HttpUrl path;
// private final String contentType;
// private final RequestBody payload;
// private final ResponseType<T> type;
//
// /**
// * Constructor for a new Request
// *
// * @param method The HTTP method to use
// * @param path The {@link HttpUrl} for the url path of the HTTP request
// * @param contentType The content type of HTTP request
// * @param payload Additional params passed as OkHttp {@link RequestBody} to the HTTP request
// */
// Request(String method, HttpUrl path, String contentType, RequestBody payload, ResponseType<T> type) {
// this.method = method;
// this.path = path;
// this.contentType = contentType;
// this.payload = payload;
// this.type = type;
// }
//
// /**
// * Gets the HTTP method.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
//
// /**
// * Gets url path for the specific API in the request.
// *
// * @return the url path as {@link HttpUrl}
// */
// public HttpUrl getPath() {
// return path;
// }
//
// /**
// * Gets HTTP request content type.
// *
// * @return the content type as a String
// */
// public String getContentType() {
// return contentType;
// }
//
// /**
// * Gets payload (request params).
// *
// * @return the payload as a {@link RequestBody}
// */
// public RequestBody getPayload() {
// return payload;
// }
//
// public ResponseType<T> getType() {
// return type;
// }
// }
// Path: src/test/java/co/omise/live/LiveForexRequestTest.java
import co.omise.models.Forex;
import co.omise.requests.Request;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
package co.omise.live;
public class LiveForexRequestTest extends BaseLiveTest {
@Test
@Ignore("only hit when test on live.")
public void TestGetForex() throws Exception { | Request<Forex> request = new Forex.GetRequestBuilder("usd") |
omise/omise-java | src/test/java/co/omise/live/LiveForexRequestTest.java | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/requests/Request.java
// public class Request<T extends OmiseObjectBase> {
// private final String method;
// private final HttpUrl path;
// private final String contentType;
// private final RequestBody payload;
// private final ResponseType<T> type;
//
// /**
// * Constructor for a new Request
// *
// * @param method The HTTP method to use
// * @param path The {@link HttpUrl} for the url path of the HTTP request
// * @param contentType The content type of HTTP request
// * @param payload Additional params passed as OkHttp {@link RequestBody} to the HTTP request
// */
// Request(String method, HttpUrl path, String contentType, RequestBody payload, ResponseType<T> type) {
// this.method = method;
// this.path = path;
// this.contentType = contentType;
// this.payload = payload;
// this.type = type;
// }
//
// /**
// * Gets the HTTP method.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
//
// /**
// * Gets url path for the specific API in the request.
// *
// * @return the url path as {@link HttpUrl}
// */
// public HttpUrl getPath() {
// return path;
// }
//
// /**
// * Gets HTTP request content type.
// *
// * @return the content type as a String
// */
// public String getContentType() {
// return contentType;
// }
//
// /**
// * Gets payload (request params).
// *
// * @return the payload as a {@link RequestBody}
// */
// public RequestBody getPayload() {
// return payload;
// }
//
// public ResponseType<T> getType() {
// return type;
// }
// }
| import co.omise.models.Forex;
import co.omise.requests.Request;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*; | package co.omise.live;
public class LiveForexRequestTest extends BaseLiveTest {
@Test
@Ignore("only hit when test on live.")
public void TestGetForex() throws Exception { | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/requests/Request.java
// public class Request<T extends OmiseObjectBase> {
// private final String method;
// private final HttpUrl path;
// private final String contentType;
// private final RequestBody payload;
// private final ResponseType<T> type;
//
// /**
// * Constructor for a new Request
// *
// * @param method The HTTP method to use
// * @param path The {@link HttpUrl} for the url path of the HTTP request
// * @param contentType The content type of HTTP request
// * @param payload Additional params passed as OkHttp {@link RequestBody} to the HTTP request
// */
// Request(String method, HttpUrl path, String contentType, RequestBody payload, ResponseType<T> type) {
// this.method = method;
// this.path = path;
// this.contentType = contentType;
// this.payload = payload;
// this.type = type;
// }
//
// /**
// * Gets the HTTP method.
// *
// * @return the HTTP method
// */
// public String getMethod() {
// return method;
// }
//
// /**
// * Gets url path for the specific API in the request.
// *
// * @return the url path as {@link HttpUrl}
// */
// public HttpUrl getPath() {
// return path;
// }
//
// /**
// * Gets HTTP request content type.
// *
// * @return the content type as a String
// */
// public String getContentType() {
// return contentType;
// }
//
// /**
// * Gets payload (request params).
// *
// * @return the payload as a {@link RequestBody}
// */
// public RequestBody getPayload() {
// return payload;
// }
//
// public ResponseType<T> getType() {
// return type;
// }
// }
// Path: src/test/java/co/omise/live/LiveForexRequestTest.java
import co.omise.models.Forex;
import co.omise.requests.Request;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
package co.omise.live;
public class LiveForexRequestTest extends BaseLiveTest {
@Test
@Ignore("only hit when test on live.")
public void TestGetForex() throws Exception { | Request<Forex> request = new Forex.GetRequestBuilder("usd") |
omise/omise-java | src/test/java/co/omise/ConfigurerTest.java | // Path: src/test/java/co/omise/ConfigTest.java
// public class ConfigTest extends OmiseTest {
// static final String JAVA_VERSION = System.getProperty("java.version");
// static final String PKG_VERSION = Client.class.getPackage().getImplementationVersion();
//
// static final String API_VERSION = "new-shiny-version";
// static final String PKEY = "pkey_test_123";
// static final String SKEY = "skey_test_123";
//
// @Test
// public void testCtor() {
// Config config = config();
// assertEquals(API_VERSION, config.apiVersion());
// assertEquals(PKEY, config.publicKey());
// assertEquals(SKEY, config.secretKey());
// }
//
// @Test
// public void testUserAgent() {
// StringBuilder builder = new StringBuilder();
// builder.append("OmiseJava/");
// builder.append(PKG_VERSION);
// builder.append(" OmiseAPI/");
// builder.append(API_VERSION);
// builder.append(" Java/");
// builder.append(JAVA_VERSION);
//
// assertEquals(builder.toString(), config().userAgent());
// }
//
// static Config config() {
// return new Config(API_VERSION, PKEY, SKEY);
// }
// }
| import okhttp3.Credentials;
import okhttp3.Request;
import org.junit.Test;
import static co.omise.ConfigTest.*; | .build());
assertEquals(API_VERSION, req.header("Omise-Version"));
}
@Test
public void testVaultRequest() {
Request req = configure(new Request.Builder()
.url("https://vault.omise.co/tokens")
.build());
String authorization = req.header("Authorization");
assertEquals(authorization, Credentials.basic(PKEY, "x"));
}
@Test
public void testApiRequest() {
Request req = configure(new Request.Builder()
.url("https://api.omise.co/charges")
.build());
String authorization = req.header("Authorization");
assertEquals(authorization, Credentials.basic(SKEY, "x"));
}
private Request configure(Request req) {
return Configurer.configure(config(), req);
}
private Config config() { | // Path: src/test/java/co/omise/ConfigTest.java
// public class ConfigTest extends OmiseTest {
// static final String JAVA_VERSION = System.getProperty("java.version");
// static final String PKG_VERSION = Client.class.getPackage().getImplementationVersion();
//
// static final String API_VERSION = "new-shiny-version";
// static final String PKEY = "pkey_test_123";
// static final String SKEY = "skey_test_123";
//
// @Test
// public void testCtor() {
// Config config = config();
// assertEquals(API_VERSION, config.apiVersion());
// assertEquals(PKEY, config.publicKey());
// assertEquals(SKEY, config.secretKey());
// }
//
// @Test
// public void testUserAgent() {
// StringBuilder builder = new StringBuilder();
// builder.append("OmiseJava/");
// builder.append(PKG_VERSION);
// builder.append(" OmiseAPI/");
// builder.append(API_VERSION);
// builder.append(" Java/");
// builder.append(JAVA_VERSION);
//
// assertEquals(builder.toString(), config().userAgent());
// }
//
// static Config config() {
// return new Config(API_VERSION, PKEY, SKEY);
// }
// }
// Path: src/test/java/co/omise/ConfigurerTest.java
import okhttp3.Credentials;
import okhttp3.Request;
import org.junit.Test;
import static co.omise.ConfigTest.*;
.build());
assertEquals(API_VERSION, req.header("Omise-Version"));
}
@Test
public void testVaultRequest() {
Request req = configure(new Request.Builder()
.url("https://vault.omise.co/tokens")
.build());
String authorization = req.header("Authorization");
assertEquals(authorization, Credentials.basic(PKEY, "x"));
}
@Test
public void testApiRequest() {
Request req = configure(new Request.Builder()
.url("https://api.omise.co/charges")
.build());
String authorization = req.header("Authorization");
assertEquals(authorization, Credentials.basic(SKEY, "x"));
}
private Request configure(Request req) {
return Configurer.configure(config(), req);
}
private Config config() { | return ConfigTest.config(); |
omise/omise-java | src/test/java/co/omise/SerializerTest.java | // Path: src/main/java/co/omise/models/OmiseObjectBase.java
// public abstract class OmiseObjectBase implements OmiseObject, Serializable {
//
// private String object;
// private String location;
//
// public OmiseObjectBase() {
// }
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
// }
//
// Path: src/main/java/co/omise/models/Params.java
// public abstract class Params {
// private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
//
// /**
// * Returns a map of query string key values to add to an HTTP operation's URL.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link Map} containing keys and values to adds to the URL.
// */
// public Map<String, String> query(Serializer serializer) {
// return Collections.unmodifiableMap(new HashMap<String, String>());
// }
//
// /**
// * Returns the {@link RequestBody} to send with the HTTP request. The default implementation serializes
// * the instance into JSON format and builds an HTTP {@link RequestBody} containing the serialized data.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link RequestBody} to send with the HTTP request.
// * @throws IOException on serialization errors.
// */
// public RequestBody body(Serializer serializer) throws IOException {
// if (serializer == null) {
// serializer = Serializer.defaultSerializer();
// }
//
// ByteArrayOutputStream stream = new ByteArrayOutputStream(4096);
// serializer.serializeParams(stream, this);
// return RequestBody.create(JSON_MEDIA_TYPE, stream.toByteArray());
// }
// }
| import co.omise.models.OmiseObjectBase;
import co.omise.models.Params;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map; | map.put("object", "dummy");
map.put("hello", "world");
Dummy dummy = serializer().deserializeFromMap(map, Dummy.class);
assertEquals("/404", dummy.getLocation());
assertEquals("dummy", dummy.getObject());
assertEquals("world", dummy.getHello());
}
@Test
public void testDeserializeMapTypeRef() {
Map<String, Object> map = Maps.newHashMapWithExpectedSize(4);
map.put("location", "/404");
map.put("object", "dummy");
map.put("hello", "world");
Dummy dummy = serializer().deserializeFromMap(map, new TypeReference<Dummy>() {
});
assertEquals("/404", dummy.getLocation());
assertEquals("dummy", dummy.getObject());
assertEquals("world", dummy.getHello());
}
private Serializer serializer() {
return Serializer.defaultSerializer();
}
| // Path: src/main/java/co/omise/models/OmiseObjectBase.java
// public abstract class OmiseObjectBase implements OmiseObject, Serializable {
//
// private String object;
// private String location;
//
// public OmiseObjectBase() {
// }
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
// }
//
// Path: src/main/java/co/omise/models/Params.java
// public abstract class Params {
// private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
//
// /**
// * Returns a map of query string key values to add to an HTTP operation's URL.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link Map} containing keys and values to adds to the URL.
// */
// public Map<String, String> query(Serializer serializer) {
// return Collections.unmodifiableMap(new HashMap<String, String>());
// }
//
// /**
// * Returns the {@link RequestBody} to send with the HTTP request. The default implementation serializes
// * the instance into JSON format and builds an HTTP {@link RequestBody} containing the serialized data.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link RequestBody} to send with the HTTP request.
// * @throws IOException on serialization errors.
// */
// public RequestBody body(Serializer serializer) throws IOException {
// if (serializer == null) {
// serializer = Serializer.defaultSerializer();
// }
//
// ByteArrayOutputStream stream = new ByteArrayOutputStream(4096);
// serializer.serializeParams(stream, this);
// return RequestBody.create(JSON_MEDIA_TYPE, stream.toByteArray());
// }
// }
// Path: src/test/java/co/omise/SerializerTest.java
import co.omise.models.OmiseObjectBase;
import co.omise.models.Params;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
map.put("object", "dummy");
map.put("hello", "world");
Dummy dummy = serializer().deserializeFromMap(map, Dummy.class);
assertEquals("/404", dummy.getLocation());
assertEquals("dummy", dummy.getObject());
assertEquals("world", dummy.getHello());
}
@Test
public void testDeserializeMapTypeRef() {
Map<String, Object> map = Maps.newHashMapWithExpectedSize(4);
map.put("location", "/404");
map.put("object", "dummy");
map.put("hello", "world");
Dummy dummy = serializer().deserializeFromMap(map, new TypeReference<Dummy>() {
});
assertEquals("/404", dummy.getLocation());
assertEquals("dummy", dummy.getObject());
assertEquals("world", dummy.getHello());
}
private Serializer serializer() {
return Serializer.defaultSerializer();
}
| public static final class Dummy extends OmiseObjectBase { |
omise/omise-java | src/test/java/co/omise/SerializerTest.java | // Path: src/main/java/co/omise/models/OmiseObjectBase.java
// public abstract class OmiseObjectBase implements OmiseObject, Serializable {
//
// private String object;
// private String location;
//
// public OmiseObjectBase() {
// }
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
// }
//
// Path: src/main/java/co/omise/models/Params.java
// public abstract class Params {
// private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
//
// /**
// * Returns a map of query string key values to add to an HTTP operation's URL.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link Map} containing keys and values to adds to the URL.
// */
// public Map<String, String> query(Serializer serializer) {
// return Collections.unmodifiableMap(new HashMap<String, String>());
// }
//
// /**
// * Returns the {@link RequestBody} to send with the HTTP request. The default implementation serializes
// * the instance into JSON format and builds an HTTP {@link RequestBody} containing the serialized data.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link RequestBody} to send with the HTTP request.
// * @throws IOException on serialization errors.
// */
// public RequestBody body(Serializer serializer) throws IOException {
// if (serializer == null) {
// serializer = Serializer.defaultSerializer();
// }
//
// ByteArrayOutputStream stream = new ByteArrayOutputStream(4096);
// serializer.serializeParams(stream, this);
// return RequestBody.create(JSON_MEDIA_TYPE, stream.toByteArray());
// }
// }
| import co.omise.models.OmiseObjectBase;
import co.omise.models.Params;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map; |
assertEquals("/404", dummy.getLocation());
assertEquals("dummy", dummy.getObject());
assertEquals("world", dummy.getHello());
}
private Serializer serializer() {
return Serializer.defaultSerializer();
}
public static final class Dummy extends OmiseObjectBase {
private String hello;
public Dummy() {
setLocation("/404");
setObject("dummy");
setHello("world");
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
| // Path: src/main/java/co/omise/models/OmiseObjectBase.java
// public abstract class OmiseObjectBase implements OmiseObject, Serializable {
//
// private String object;
// private String location;
//
// public OmiseObjectBase() {
// }
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
// }
//
// Path: src/main/java/co/omise/models/Params.java
// public abstract class Params {
// private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
//
// /**
// * Returns a map of query string key values to add to an HTTP operation's URL.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link Map} containing keys and values to adds to the URL.
// */
// public Map<String, String> query(Serializer serializer) {
// return Collections.unmodifiableMap(new HashMap<String, String>());
// }
//
// /**
// * Returns the {@link RequestBody} to send with the HTTP request. The default implementation serializes
// * the instance into JSON format and builds an HTTP {@link RequestBody} containing the serialized data.
// *
// * @param serializer The {@link Serializer} to use to serialize parameter data.
// * Or `null` to use the default serializer.
// * @return An {@link RequestBody} to send with the HTTP request.
// * @throws IOException on serialization errors.
// */
// public RequestBody body(Serializer serializer) throws IOException {
// if (serializer == null) {
// serializer = Serializer.defaultSerializer();
// }
//
// ByteArrayOutputStream stream = new ByteArrayOutputStream(4096);
// serializer.serializeParams(stream, this);
// return RequestBody.create(JSON_MEDIA_TYPE, stream.toByteArray());
// }
// }
// Path: src/test/java/co/omise/SerializerTest.java
import co.omise.models.OmiseObjectBase;
import co.omise.models.Params;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
assertEquals("/404", dummy.getLocation());
assertEquals("dummy", dummy.getObject());
assertEquals("world", dummy.getHello());
}
private Serializer serializer() {
return Serializer.defaultSerializer();
}
public static final class Dummy extends OmiseObjectBase {
private String hello;
public Dummy() {
setLocation("/404");
setObject("dummy");
setHello("world");
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
| public static final class DummyParams extends Params { |
omise/omise-java | src/test/java/co/omise/testutils/TestInterceptor.java | // Path: src/test/java/co/omise/OmiseTest.java
// public abstract class OmiseTest extends Assert {
// public byte[] getResourceBytes(String path) throws IOException {
// InputStream stream = getClass().getResourceAsStream(path);
// return stream == null ? null : ByteStreams.toByteArray(stream);
// }
// }
| import co.omise.OmiseTest;
import okhttp3.*;
import java.io.IOException; | package co.omise.testutils;
public class TestInterceptor implements Interceptor {
private static final MediaType jsonMediaType = MediaType.parse("application/json");
| // Path: src/test/java/co/omise/OmiseTest.java
// public abstract class OmiseTest extends Assert {
// public byte[] getResourceBytes(String path) throws IOException {
// InputStream stream = getClass().getResourceAsStream(path);
// return stream == null ? null : ByteStreams.toByteArray(stream);
// }
// }
// Path: src/test/java/co/omise/testutils/TestInterceptor.java
import co.omise.OmiseTest;
import okhttp3.*;
import java.io.IOException;
package co.omise.testutils;
public class TestInterceptor implements Interceptor {
private static final MediaType jsonMediaType = MediaType.parse("application/json");
| private final OmiseTest test; |
omise/omise-java | src/test/java/co/omise/requests/CapabilityRequestTest.java | // Path: src/main/java/co/omise/models/Bank.java
// public class Bank {
// private String code;
// private String name;
// private boolean active;
//
// public String getCode() {
// return this.code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isActive() {
// return this.active;
// }
//
// public void setActive(boolean active) {
// this.active = active;
// }
// }
//
// Path: src/main/java/co/omise/models/Capability.java
// public class Capability extends Model {
// private List<String> banks;
// private String country;
// private String location;
// @JsonProperty("payment_methods")
// private List<PaymentMethod> paymentMethods;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public List<String> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<String> banks) {
// this.banks = banks;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public List<PaymentMethod> getPaymentMethods() {
// return this.paymentMethods;
// }
//
// public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
// this.paymentMethods = paymentMethods;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Capability> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "capability");
// }
//
// @Override
// protected ResponseType<Capability> type() {
// return new ResponseType<>(Capability.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
//
// Path: src/main/java/co/omise/models/PaymentMethod.java
// public class PaymentMethod extends Model {
// @JsonProperty("card_brands")
// private List<String> cardBrands;
// private List<String> currencies;
// @JsonProperty("installment_terms")
// private List<Integer> installmentTerms;
// private String name;
// private List<Bank> banks;
//
// public List<String> getCardBrands() {
// return this.cardBrands;
// }
//
// public void setCardBrands(List<String> cardBrands) {
// this.cardBrands = cardBrands;
// }
//
// public List<String> getCurrencies() {
// return this.currencies;
// }
//
// public void setCurrencies(List<String> currencies) {
// this.currencies = currencies;
// }
//
// public List<Integer> getInstallmentTerms() {
// return this.installmentTerms;
// }
//
// public void setInstallmentTerms(List<Integer> installmentTerms) {
// this.installmentTerms = installmentTerms;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Bank> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<Bank> banks) {
// this.banks = banks;
// }
// }
| import co.omise.models.Bank;
import co.omise.models.Capability;
import co.omise.models.OmiseException;
import co.omise.models.PaymentMethod;
import org.junit.Test;
import java.io.IOException;
import java.util.List; | package co.omise.requests;
public class CapabilityRequestTest extends RequestTest {
@Test | // Path: src/main/java/co/omise/models/Bank.java
// public class Bank {
// private String code;
// private String name;
// private boolean active;
//
// public String getCode() {
// return this.code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isActive() {
// return this.active;
// }
//
// public void setActive(boolean active) {
// this.active = active;
// }
// }
//
// Path: src/main/java/co/omise/models/Capability.java
// public class Capability extends Model {
// private List<String> banks;
// private String country;
// private String location;
// @JsonProperty("payment_methods")
// private List<PaymentMethod> paymentMethods;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public List<String> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<String> banks) {
// this.banks = banks;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public List<PaymentMethod> getPaymentMethods() {
// return this.paymentMethods;
// }
//
// public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
// this.paymentMethods = paymentMethods;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Capability> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "capability");
// }
//
// @Override
// protected ResponseType<Capability> type() {
// return new ResponseType<>(Capability.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
//
// Path: src/main/java/co/omise/models/PaymentMethod.java
// public class PaymentMethod extends Model {
// @JsonProperty("card_brands")
// private List<String> cardBrands;
// private List<String> currencies;
// @JsonProperty("installment_terms")
// private List<Integer> installmentTerms;
// private String name;
// private List<Bank> banks;
//
// public List<String> getCardBrands() {
// return this.cardBrands;
// }
//
// public void setCardBrands(List<String> cardBrands) {
// this.cardBrands = cardBrands;
// }
//
// public List<String> getCurrencies() {
// return this.currencies;
// }
//
// public void setCurrencies(List<String> currencies) {
// this.currencies = currencies;
// }
//
// public List<Integer> getInstallmentTerms() {
// return this.installmentTerms;
// }
//
// public void setInstallmentTerms(List<Integer> installmentTerms) {
// this.installmentTerms = installmentTerms;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Bank> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<Bank> banks) {
// this.banks = banks;
// }
// }
// Path: src/test/java/co/omise/requests/CapabilityRequestTest.java
import co.omise.models.Bank;
import co.omise.models.Capability;
import co.omise.models.OmiseException;
import co.omise.models.PaymentMethod;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
package co.omise.requests;
public class CapabilityRequestTest extends RequestTest {
@Test | public void testGet() throws IOException, OmiseException { |
omise/omise-java | src/test/java/co/omise/requests/CapabilityRequestTest.java | // Path: src/main/java/co/omise/models/Bank.java
// public class Bank {
// private String code;
// private String name;
// private boolean active;
//
// public String getCode() {
// return this.code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isActive() {
// return this.active;
// }
//
// public void setActive(boolean active) {
// this.active = active;
// }
// }
//
// Path: src/main/java/co/omise/models/Capability.java
// public class Capability extends Model {
// private List<String> banks;
// private String country;
// private String location;
// @JsonProperty("payment_methods")
// private List<PaymentMethod> paymentMethods;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public List<String> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<String> banks) {
// this.banks = banks;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public List<PaymentMethod> getPaymentMethods() {
// return this.paymentMethods;
// }
//
// public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
// this.paymentMethods = paymentMethods;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Capability> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "capability");
// }
//
// @Override
// protected ResponseType<Capability> type() {
// return new ResponseType<>(Capability.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
//
// Path: src/main/java/co/omise/models/PaymentMethod.java
// public class PaymentMethod extends Model {
// @JsonProperty("card_brands")
// private List<String> cardBrands;
// private List<String> currencies;
// @JsonProperty("installment_terms")
// private List<Integer> installmentTerms;
// private String name;
// private List<Bank> banks;
//
// public List<String> getCardBrands() {
// return this.cardBrands;
// }
//
// public void setCardBrands(List<String> cardBrands) {
// this.cardBrands = cardBrands;
// }
//
// public List<String> getCurrencies() {
// return this.currencies;
// }
//
// public void setCurrencies(List<String> currencies) {
// this.currencies = currencies;
// }
//
// public List<Integer> getInstallmentTerms() {
// return this.installmentTerms;
// }
//
// public void setInstallmentTerms(List<Integer> installmentTerms) {
// this.installmentTerms = installmentTerms;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Bank> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<Bank> banks) {
// this.banks = banks;
// }
// }
| import co.omise.models.Bank;
import co.omise.models.Capability;
import co.omise.models.OmiseException;
import co.omise.models.PaymentMethod;
import org.junit.Test;
import java.io.IOException;
import java.util.List; | package co.omise.requests;
public class CapabilityRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException {
Requester requester = getTestRequester(); | // Path: src/main/java/co/omise/models/Bank.java
// public class Bank {
// private String code;
// private String name;
// private boolean active;
//
// public String getCode() {
// return this.code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isActive() {
// return this.active;
// }
//
// public void setActive(boolean active) {
// this.active = active;
// }
// }
//
// Path: src/main/java/co/omise/models/Capability.java
// public class Capability extends Model {
// private List<String> banks;
// private String country;
// private String location;
// @JsonProperty("payment_methods")
// private List<PaymentMethod> paymentMethods;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public List<String> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<String> banks) {
// this.banks = banks;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public List<PaymentMethod> getPaymentMethods() {
// return this.paymentMethods;
// }
//
// public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
// this.paymentMethods = paymentMethods;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Capability> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "capability");
// }
//
// @Override
// protected ResponseType<Capability> type() {
// return new ResponseType<>(Capability.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
//
// Path: src/main/java/co/omise/models/PaymentMethod.java
// public class PaymentMethod extends Model {
// @JsonProperty("card_brands")
// private List<String> cardBrands;
// private List<String> currencies;
// @JsonProperty("installment_terms")
// private List<Integer> installmentTerms;
// private String name;
// private List<Bank> banks;
//
// public List<String> getCardBrands() {
// return this.cardBrands;
// }
//
// public void setCardBrands(List<String> cardBrands) {
// this.cardBrands = cardBrands;
// }
//
// public List<String> getCurrencies() {
// return this.currencies;
// }
//
// public void setCurrencies(List<String> currencies) {
// this.currencies = currencies;
// }
//
// public List<Integer> getInstallmentTerms() {
// return this.installmentTerms;
// }
//
// public void setInstallmentTerms(List<Integer> installmentTerms) {
// this.installmentTerms = installmentTerms;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Bank> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<Bank> banks) {
// this.banks = banks;
// }
// }
// Path: src/test/java/co/omise/requests/CapabilityRequestTest.java
import co.omise.models.Bank;
import co.omise.models.Capability;
import co.omise.models.OmiseException;
import co.omise.models.PaymentMethod;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
package co.omise.requests;
public class CapabilityRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException {
Requester requester = getTestRequester(); | Request<Capability> request = new Capability.GetRequestBuilder().build(); |
omise/omise-java | src/test/java/co/omise/requests/CapabilityRequestTest.java | // Path: src/main/java/co/omise/models/Bank.java
// public class Bank {
// private String code;
// private String name;
// private boolean active;
//
// public String getCode() {
// return this.code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isActive() {
// return this.active;
// }
//
// public void setActive(boolean active) {
// this.active = active;
// }
// }
//
// Path: src/main/java/co/omise/models/Capability.java
// public class Capability extends Model {
// private List<String> banks;
// private String country;
// private String location;
// @JsonProperty("payment_methods")
// private List<PaymentMethod> paymentMethods;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public List<String> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<String> banks) {
// this.banks = banks;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public List<PaymentMethod> getPaymentMethods() {
// return this.paymentMethods;
// }
//
// public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
// this.paymentMethods = paymentMethods;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Capability> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "capability");
// }
//
// @Override
// protected ResponseType<Capability> type() {
// return new ResponseType<>(Capability.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
//
// Path: src/main/java/co/omise/models/PaymentMethod.java
// public class PaymentMethod extends Model {
// @JsonProperty("card_brands")
// private List<String> cardBrands;
// private List<String> currencies;
// @JsonProperty("installment_terms")
// private List<Integer> installmentTerms;
// private String name;
// private List<Bank> banks;
//
// public List<String> getCardBrands() {
// return this.cardBrands;
// }
//
// public void setCardBrands(List<String> cardBrands) {
// this.cardBrands = cardBrands;
// }
//
// public List<String> getCurrencies() {
// return this.currencies;
// }
//
// public void setCurrencies(List<String> currencies) {
// this.currencies = currencies;
// }
//
// public List<Integer> getInstallmentTerms() {
// return this.installmentTerms;
// }
//
// public void setInstallmentTerms(List<Integer> installmentTerms) {
// this.installmentTerms = installmentTerms;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Bank> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<Bank> banks) {
// this.banks = banks;
// }
// }
| import co.omise.models.Bank;
import co.omise.models.Capability;
import co.omise.models.OmiseException;
import co.omise.models.PaymentMethod;
import org.junit.Test;
import java.io.IOException;
import java.util.List; | package co.omise.requests;
public class CapabilityRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException {
Requester requester = getTestRequester();
Request<Capability> request = new Capability.GetRequestBuilder().build();
Capability capability = requester.sendRequest(request);
assertRequested("GET", "/capability", 200);
assertEquals("capability", capability.getObject());
assertEquals("/capability", capability.getLocation());
assertTrue(capability.getBanks().size() > 0);
assertTrue(capability.getPaymentMethods().size() > 0);
assertFalse(capability.isZeroInterestInstallments());
| // Path: src/main/java/co/omise/models/Bank.java
// public class Bank {
// private String code;
// private String name;
// private boolean active;
//
// public String getCode() {
// return this.code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isActive() {
// return this.active;
// }
//
// public void setActive(boolean active) {
// this.active = active;
// }
// }
//
// Path: src/main/java/co/omise/models/Capability.java
// public class Capability extends Model {
// private List<String> banks;
// private String country;
// private String location;
// @JsonProperty("payment_methods")
// private List<PaymentMethod> paymentMethods;
// @JsonProperty("zero_interest_installments")
// private boolean zeroInterestInstallments;
//
// public List<String> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<String> banks) {
// this.banks = banks;
// }
//
// public String getCountry() {
// return this.country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public List<PaymentMethod> getPaymentMethods() {
// return this.paymentMethods;
// }
//
// public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
// this.paymentMethods = paymentMethods;
// }
//
// public boolean isZeroInterestInstallments() {
// return this.zeroInterestInstallments;
// }
//
// public void setZeroInterestInstallments(boolean zeroInterestInstallments) {
// this.zeroInterestInstallments = zeroInterestInstallments;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Capability> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "capability");
// }
//
// @Override
// protected ResponseType<Capability> type() {
// return new ResponseType<>(Capability.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
//
// Path: src/main/java/co/omise/models/PaymentMethod.java
// public class PaymentMethod extends Model {
// @JsonProperty("card_brands")
// private List<String> cardBrands;
// private List<String> currencies;
// @JsonProperty("installment_terms")
// private List<Integer> installmentTerms;
// private String name;
// private List<Bank> banks;
//
// public List<String> getCardBrands() {
// return this.cardBrands;
// }
//
// public void setCardBrands(List<String> cardBrands) {
// this.cardBrands = cardBrands;
// }
//
// public List<String> getCurrencies() {
// return this.currencies;
// }
//
// public void setCurrencies(List<String> currencies) {
// this.currencies = currencies;
// }
//
// public List<Integer> getInstallmentTerms() {
// return this.installmentTerms;
// }
//
// public void setInstallmentTerms(List<Integer> installmentTerms) {
// this.installmentTerms = installmentTerms;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<Bank> getBanks() {
// return this.banks;
// }
//
// public void setBanks(List<Bank> banks) {
// this.banks = banks;
// }
// }
// Path: src/test/java/co/omise/requests/CapabilityRequestTest.java
import co.omise.models.Bank;
import co.omise.models.Capability;
import co.omise.models.OmiseException;
import co.omise.models.PaymentMethod;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
package co.omise.requests;
public class CapabilityRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException {
Requester requester = getTestRequester();
Request<Capability> request = new Capability.GetRequestBuilder().build();
Capability capability = requester.sendRequest(request);
assertRequested("GET", "/capability", 200);
assertEquals("capability", capability.getObject());
assertEquals("/capability", capability.getLocation());
assertTrue(capability.getBanks().size() > 0);
assertTrue(capability.getPaymentMethods().size() > 0);
assertFalse(capability.isZeroInterestInstallments());
| List<PaymentMethod> paymentMethods = capability.getPaymentMethods(); |
omise/omise-java | src/test/java/co/omise/requests/BalanceRequestTest.java | // Path: src/main/java/co/omise/models/Balance.java
// public class Balance extends Model {
// private String currency;
// private String location;
// private long reserve;
// private long total;
// private long transferable;
//
// public String getCurrency() {
// return this.currency;
// }
//
// public void setCurrency(String currency) {
// this.currency = currency;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public long getReserve() {
// return this.reserve;
// }
//
// public void setReserve(long reserve) {
// this.reserve = reserve;
// }
//
// public long getTotal() {
// return this.total;
// }
//
// public void setTotal(long total) {
// this.total = total;
// }
//
// public long getTransferable() {
// return this.transferable;
// }
//
// public void setTransferable(long transferable) {
// this.transferable = transferable;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Balance> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "balance");
// }
//
// @Override
// protected ResponseType<Balance> type() {
// return new ResponseType<>(Balance.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
| import co.omise.models.Balance;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException; | package co.omise.requests;
public class BalanceRequestTest extends RequestTest {
@Test | // Path: src/main/java/co/omise/models/Balance.java
// public class Balance extends Model {
// private String currency;
// private String location;
// private long reserve;
// private long total;
// private long transferable;
//
// public String getCurrency() {
// return this.currency;
// }
//
// public void setCurrency(String currency) {
// this.currency = currency;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public long getReserve() {
// return this.reserve;
// }
//
// public void setReserve(long reserve) {
// this.reserve = reserve;
// }
//
// public long getTotal() {
// return this.total;
// }
//
// public void setTotal(long total) {
// this.total = total;
// }
//
// public long getTransferable() {
// return this.transferable;
// }
//
// public void setTransferable(long transferable) {
// this.transferable = transferable;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Balance> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "balance");
// }
//
// @Override
// protected ResponseType<Balance> type() {
// return new ResponseType<>(Balance.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
// Path: src/test/java/co/omise/requests/BalanceRequestTest.java
import co.omise.models.Balance;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException;
package co.omise.requests;
public class BalanceRequestTest extends RequestTest {
@Test | public void testGet() throws IOException, OmiseException { |
omise/omise-java | src/test/java/co/omise/requests/BalanceRequestTest.java | // Path: src/main/java/co/omise/models/Balance.java
// public class Balance extends Model {
// private String currency;
// private String location;
// private long reserve;
// private long total;
// private long transferable;
//
// public String getCurrency() {
// return this.currency;
// }
//
// public void setCurrency(String currency) {
// this.currency = currency;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public long getReserve() {
// return this.reserve;
// }
//
// public void setReserve(long reserve) {
// this.reserve = reserve;
// }
//
// public long getTotal() {
// return this.total;
// }
//
// public void setTotal(long total) {
// this.total = total;
// }
//
// public long getTransferable() {
// return this.transferable;
// }
//
// public void setTransferable(long transferable) {
// this.transferable = transferable;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Balance> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "balance");
// }
//
// @Override
// protected ResponseType<Balance> type() {
// return new ResponseType<>(Balance.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
| import co.omise.models.Balance;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException; | package co.omise.requests;
public class BalanceRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException {
Requester requester = getTestRequester(); | // Path: src/main/java/co/omise/models/Balance.java
// public class Balance extends Model {
// private String currency;
// private String location;
// private long reserve;
// private long total;
// private long transferable;
//
// public String getCurrency() {
// return this.currency;
// }
//
// public void setCurrency(String currency) {
// this.currency = currency;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public long getReserve() {
// return this.reserve;
// }
//
// public void setReserve(long reserve) {
// this.reserve = reserve;
// }
//
// public long getTotal() {
// return this.total;
// }
//
// public void setTotal(long total) {
// this.total = total;
// }
//
// public long getTransferable() {
// return this.transferable;
// }
//
// public void setTransferable(long transferable) {
// this.transferable = transferable;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Balance> {
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "balance");
// }
//
// @Override
// protected ResponseType<Balance> type() {
// return new ResponseType<>(Balance.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
// Path: src/test/java/co/omise/requests/BalanceRequestTest.java
import co.omise.models.Balance;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException;
package co.omise.requests;
public class BalanceRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException {
Requester requester = getTestRequester(); | Request<Balance> getBalanceRequest = new Balance.GetRequestBuilder().build(); |
omise/omise-java | src/test/java/co/omise/requests/ForexRequestTest.java | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
| import co.omise.models.Forex;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException; | package co.omise.requests;
public class ForexRequestTest extends RequestTest {
@Test | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
// Path: src/test/java/co/omise/requests/ForexRequestTest.java
import co.omise.models.Forex;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException;
package co.omise.requests;
public class ForexRequestTest extends RequestTest {
@Test | public void testGet() throws IOException, OmiseException { |
omise/omise-java | src/test/java/co/omise/requests/ForexRequestTest.java | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
| import co.omise.models.Forex;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException; | package co.omise.requests;
public class ForexRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException { | // Path: src/main/java/co/omise/models/Forex.java
// public class Forex extends Model {
// private String base;
// private String location;
// private String quote;
// private Double rate;
//
// public String getBase() {
// return this.base;
// }
//
// public void setBase(String base) {
// this.base = base;
// }
//
// public String getLocation() {
// return this.location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getQuote() {
// return this.quote;
// }
//
// public void setQuote(String quote) {
// this.quote = quote;
// }
//
// public Double getRate() {
// return this.rate;
// }
//
// public void setRate(Double rate) {
// this.rate = rate;
// }
//
// public static class GetRequestBuilder extends RequestBuilder<Forex> {
// private String currency;
// public GetRequestBuilder(String currency) {
// this.currency = currency;
// }
//
// @Override
// protected String method() {
// return GET;
// }
//
// @Override
// protected HttpUrl path() {
// return buildUrl(Endpoint.API, "forex", currency);
// }
//
// @Override
// protected ResponseType<Forex> type() {
// return new ResponseType<>(Forex.class);
// }
// }
// }
//
// Path: src/main/java/co/omise/models/OmiseException.java
// public class OmiseException extends Exception implements OmiseObject {
// private String object;
// private String location;
// private String code;
// private int httpStatusCode;
// private String message;
//
// @Override
// public String getObject() {
// return object;
// }
//
// @Override
// public void setObject(String object) {
// this.object = object;
// }
//
// @Override
// public String getLocation() {
// return location;
// }
//
// @Override
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public int getHttpStatusCode() {
// return httpStatusCode;
// }
//
// public void setHttpStatusCode(int httpStatusCode) {
// this.httpStatusCode = httpStatusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public String toString() {
// return "(" + Integer.toString(httpStatusCode) + "/" + code + ") " + message;
// }
// }
// Path: src/test/java/co/omise/requests/ForexRequestTest.java
import co.omise.models.Forex;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException;
package co.omise.requests;
public class ForexRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException { | Request<Forex> request = new Forex.GetRequestBuilder("usd") |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/support/MethodInvokingStateTransitionFactoryBean.java | // Path: src/main/java/org/springframework/extensions/workflow/TransitionAction.java
// public interface TransitionAction {
//
// void perform(TransitionActionContext actionContext) throws Exception;
//
// }
| import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.extensions.workflow.TransitionAction; | package org.springframework.extensions.workflow.support;
/**
* @author janm
*/
public class MethodInvokingStateTransitionFactoryBean implements FactoryBean, InitializingBean {
private Object targetObject;
private String methodName; | // Path: src/main/java/org/springframework/extensions/workflow/TransitionAction.java
// public interface TransitionAction {
//
// void perform(TransitionActionContext actionContext) throws Exception;
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/support/MethodInvokingStateTransitionFactoryBean.java
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.extensions.workflow.TransitionAction;
package org.springframework.extensions.workflow.support;
/**
* @author janm
*/
public class MethodInvokingStateTransitionFactoryBean implements FactoryBean, InitializingBean {
private Object targetObject;
private String methodName; | private TransitionAction transition; |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/FlowDefinition.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorSource.java
// public interface FlowInstanceDescriptorSource {
//
// FlowInstanceDescriptor createDescriptor();
//
// }
| import org.springframework.util.Assert;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorSource;
import java.util.Set;
import java.util.HashSet;
import java.io.Serializable; | package org.springframework.extensions.workflow;
/**
* @author janm
*/
public final class FlowDefinition implements Serializable {
private static final long serialVersionUID = -4288988924628516588L;
private String id;
private Set<StateDefinition> stateDefinitions; | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorSource.java
// public interface FlowInstanceDescriptorSource {
//
// FlowInstanceDescriptor createDescriptor();
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/FlowDefinition.java
import org.springframework.util.Assert;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorSource;
import java.util.Set;
import java.util.HashSet;
import java.io.Serializable;
package org.springframework.extensions.workflow;
/**
* @author janm
*/
public final class FlowDefinition implements Serializable {
private static final long serialVersionUID = -4288988924628516588L;
private String id;
private Set<StateDefinition> stateDefinitions; | private FlowInstanceDescriptorSource flowInstanceDescriptorSource; |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/annotation/Flow.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/DefaultFlowInstanceDescriptor.java
// public class DefaultFlowInstanceDescriptor implements FlowInstanceDescriptor, Serializable {
// private static final long serialVersionUID = 2653308491709868450L;
// private String flowDefinitionId;
// private String stateDefinitionId;
// private Date dateEntered;
// private boolean withTimeouts;
//
// DefaultFlowInstanceDescriptor() {
//
// }
//
// public void setFlowDefinitionId(String flowDefinitionId) {
// this.flowDefinitionId = flowDefinitionId;
// }
//
// public String getFlowDefinitionId() {
// return this.flowDefinitionId;
// }
//
// public String getStateDefinitionId() {
// return this.stateDefinitionId;
// }
//
// public void setStateDefinitionId(String stateDefinitionId) {
// this.stateDefinitionId = stateDefinitionId;
// }
//
// public boolean isWithTimeouts() {
// return withTimeouts;
// }
//
// public void setWithTimeouts(boolean hasTimeouts) {
// this.withTimeouts = hasTimeouts;
// }
//
// public Date getDateEntered() {
// return dateEntered;
// }
//
// public void setDateEntered(Date dateEntered) {
// this.dateEntered = dateEntered;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "DefaultFlowInstanceDescriptor [" +
// "flowId=" + flowDefinitionId + ", " +
// "stateId=" + stateDefinitionId + ", " +
// "dateEntered=" + dateEntered + ", " +
// "withTimeouts=" + withTimeouts + "]";
// }
// }
| import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.DefaultFlowInstanceDescriptor;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType; | package org.springframework.extensions.workflow.annotation;
/**
* This annotation is used to identify classes that represent a flow. Together
* with the {@link org.springframework.extensions.workflow.support.FlowDefinitionPostProcessor},
* the beans with this annotations are turned into appropriate {@link org.springframework.extensions.workflow.FlowDefinition}s.
* @author janm
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Flow {
/**
* Set the flow's identity. If empty, the {@link org.springframework.extensions.workflow.support.naming.DefaultStateAndFlowNamingStrategy}
* used by the <code>FlowDefinitionPostProcessor</code> will extract a name
* from the class with this annotation.
* @return The flow identity
*/
String id() default "";
/**
* Set the FlowInstanceDescriptor implementation that represents they payload
* of the flow.
* @return The FlowInstanceDescriptor implementation
*/ | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/DefaultFlowInstanceDescriptor.java
// public class DefaultFlowInstanceDescriptor implements FlowInstanceDescriptor, Serializable {
// private static final long serialVersionUID = 2653308491709868450L;
// private String flowDefinitionId;
// private String stateDefinitionId;
// private Date dateEntered;
// private boolean withTimeouts;
//
// DefaultFlowInstanceDescriptor() {
//
// }
//
// public void setFlowDefinitionId(String flowDefinitionId) {
// this.flowDefinitionId = flowDefinitionId;
// }
//
// public String getFlowDefinitionId() {
// return this.flowDefinitionId;
// }
//
// public String getStateDefinitionId() {
// return this.stateDefinitionId;
// }
//
// public void setStateDefinitionId(String stateDefinitionId) {
// this.stateDefinitionId = stateDefinitionId;
// }
//
// public boolean isWithTimeouts() {
// return withTimeouts;
// }
//
// public void setWithTimeouts(boolean hasTimeouts) {
// this.withTimeouts = hasTimeouts;
// }
//
// public Date getDateEntered() {
// return dateEntered;
// }
//
// public void setDateEntered(Date dateEntered) {
// this.dateEntered = dateEntered;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "DefaultFlowInstanceDescriptor [" +
// "flowId=" + flowDefinitionId + ", " +
// "stateId=" + stateDefinitionId + ", " +
// "dateEntered=" + dateEntered + ", " +
// "withTimeouts=" + withTimeouts + "]";
// }
// }
// Path: src/main/java/org/springframework/extensions/workflow/annotation/Flow.java
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.DefaultFlowInstanceDescriptor;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
package org.springframework.extensions.workflow.annotation;
/**
* This annotation is used to identify classes that represent a flow. Together
* with the {@link org.springframework.extensions.workflow.support.FlowDefinitionPostProcessor},
* the beans with this annotations are turned into appropriate {@link org.springframework.extensions.workflow.FlowDefinition}s.
* @author janm
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Flow {
/**
* Set the flow's identity. If empty, the {@link org.springframework.extensions.workflow.support.naming.DefaultStateAndFlowNamingStrategy}
* used by the <code>FlowDefinitionPostProcessor</code> will extract a name
* from the class with this annotation.
* @return The flow identity
*/
String id() default "";
/**
* Set the FlowInstanceDescriptor implementation that represents they payload
* of the flow.
* @return The FlowInstanceDescriptor implementation
*/ | Class<? extends FlowInstanceDescriptor> flowInstanceDescriptorClass() default DefaultFlowInstanceDescriptor.class; |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/annotation/Flow.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/DefaultFlowInstanceDescriptor.java
// public class DefaultFlowInstanceDescriptor implements FlowInstanceDescriptor, Serializable {
// private static final long serialVersionUID = 2653308491709868450L;
// private String flowDefinitionId;
// private String stateDefinitionId;
// private Date dateEntered;
// private boolean withTimeouts;
//
// DefaultFlowInstanceDescriptor() {
//
// }
//
// public void setFlowDefinitionId(String flowDefinitionId) {
// this.flowDefinitionId = flowDefinitionId;
// }
//
// public String getFlowDefinitionId() {
// return this.flowDefinitionId;
// }
//
// public String getStateDefinitionId() {
// return this.stateDefinitionId;
// }
//
// public void setStateDefinitionId(String stateDefinitionId) {
// this.stateDefinitionId = stateDefinitionId;
// }
//
// public boolean isWithTimeouts() {
// return withTimeouts;
// }
//
// public void setWithTimeouts(boolean hasTimeouts) {
// this.withTimeouts = hasTimeouts;
// }
//
// public Date getDateEntered() {
// return dateEntered;
// }
//
// public void setDateEntered(Date dateEntered) {
// this.dateEntered = dateEntered;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "DefaultFlowInstanceDescriptor [" +
// "flowId=" + flowDefinitionId + ", " +
// "stateId=" + stateDefinitionId + ", " +
// "dateEntered=" + dateEntered + ", " +
// "withTimeouts=" + withTimeouts + "]";
// }
// }
| import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.DefaultFlowInstanceDescriptor;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType; | package org.springframework.extensions.workflow.annotation;
/**
* This annotation is used to identify classes that represent a flow. Together
* with the {@link org.springframework.extensions.workflow.support.FlowDefinitionPostProcessor},
* the beans with this annotations are turned into appropriate {@link org.springframework.extensions.workflow.FlowDefinition}s.
* @author janm
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Flow {
/**
* Set the flow's identity. If empty, the {@link org.springframework.extensions.workflow.support.naming.DefaultStateAndFlowNamingStrategy}
* used by the <code>FlowDefinitionPostProcessor</code> will extract a name
* from the class with this annotation.
* @return The flow identity
*/
String id() default "";
/**
* Set the FlowInstanceDescriptor implementation that represents they payload
* of the flow.
* @return The FlowInstanceDescriptor implementation
*/ | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/DefaultFlowInstanceDescriptor.java
// public class DefaultFlowInstanceDescriptor implements FlowInstanceDescriptor, Serializable {
// private static final long serialVersionUID = 2653308491709868450L;
// private String flowDefinitionId;
// private String stateDefinitionId;
// private Date dateEntered;
// private boolean withTimeouts;
//
// DefaultFlowInstanceDescriptor() {
//
// }
//
// public void setFlowDefinitionId(String flowDefinitionId) {
// this.flowDefinitionId = flowDefinitionId;
// }
//
// public String getFlowDefinitionId() {
// return this.flowDefinitionId;
// }
//
// public String getStateDefinitionId() {
// return this.stateDefinitionId;
// }
//
// public void setStateDefinitionId(String stateDefinitionId) {
// this.stateDefinitionId = stateDefinitionId;
// }
//
// public boolean isWithTimeouts() {
// return withTimeouts;
// }
//
// public void setWithTimeouts(boolean hasTimeouts) {
// this.withTimeouts = hasTimeouts;
// }
//
// public Date getDateEntered() {
// return dateEntered;
// }
//
// public void setDateEntered(Date dateEntered) {
// this.dateEntered = dateEntered;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "DefaultFlowInstanceDescriptor [" +
// "flowId=" + flowDefinitionId + ", " +
// "stateId=" + stateDefinitionId + ", " +
// "dateEntered=" + dateEntered + ", " +
// "withTimeouts=" + withTimeouts + "]";
// }
// }
// Path: src/main/java/org/springframework/extensions/workflow/annotation/Flow.java
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.DefaultFlowInstanceDescriptor;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
package org.springframework.extensions.workflow.annotation;
/**
* This annotation is used to identify classes that represent a flow. Together
* with the {@link org.springframework.extensions.workflow.support.FlowDefinitionPostProcessor},
* the beans with this annotations are turned into appropriate {@link org.springframework.extensions.workflow.FlowDefinition}s.
* @author janm
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Flow {
/**
* Set the flow's identity. If empty, the {@link org.springframework.extensions.workflow.support.naming.DefaultStateAndFlowNamingStrategy}
* used by the <code>FlowDefinitionPostProcessor</code> will extract a name
* from the class with this annotation.
* @return The flow identity
*/
String id() default "";
/**
* Set the FlowInstanceDescriptor implementation that represents they payload
* of the flow.
* @return The FlowInstanceDescriptor implementation
*/ | Class<? extends FlowInstanceDescriptor> flowInstanceDescriptorClass() default DefaultFlowInstanceDescriptor.class; |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/instance/session/FlowSession.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstance.java
// public interface FlowInstance extends FlowInstanceDescriptor, FlowInstanceTransitioner {
//
// FlowInstanceDescriptor getFlowInstanceDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorCreator.java
// public interface FlowInstanceDescriptorCreator {
//
// /**
// * Returns a fully constructed and initialized instance of the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
// * @return The FlowInstanceDescriptor instance
// */
// FlowInstanceDescriptor create();
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorInitializer.java
// public interface FlowInstanceDescriptorInitializer {
//
// /**
// * Perform any custom initialization of the <code>flowInstanceDescriptor</code>.
// * @param flowInstanceDescriptor An existing instance of FlowInstanceDescriptor subclass.
// */
// void initialize(FlowInstanceDescriptor flowInstanceDescriptor);
//
// }
| import org.springframework.extensions.workflow.instance.FlowInstance;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer; | package org.springframework.extensions.workflow.instance.session;
/**
* This interface provides methods to interact with the {@link FlowInstance}s.
* Typically, the FlowSession instances will be Spring beans and you will
* call its methods to obtain the <code>FlowInstance</code>s.
* @author janm
*/
public interface FlowSession {
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* This method will not initialize the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
* attached to the <code>FlowDefinition</code>, it will only call its default constructor. To create the descriptor
* yourself, call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator)};
* to perform custom initialization on an instance of the <code>FlowInstanceDescriptor</code>,
* call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer)}
* @param id The identity of the flow, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorCreator.create()</code> to obtain an
* instance of the <code>FlowInstanceDescriptor</code> for this flow instance.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorCreator The implementaiton of the FlowInstanceDescriptorCreator, never <code>null</code>
* @return The FlowInstance at the starting state
*/ | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstance.java
// public interface FlowInstance extends FlowInstanceDescriptor, FlowInstanceTransitioner {
//
// FlowInstanceDescriptor getFlowInstanceDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorCreator.java
// public interface FlowInstanceDescriptorCreator {
//
// /**
// * Returns a fully constructed and initialized instance of the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
// * @return The FlowInstanceDescriptor instance
// */
// FlowInstanceDescriptor create();
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorInitializer.java
// public interface FlowInstanceDescriptorInitializer {
//
// /**
// * Perform any custom initialization of the <code>flowInstanceDescriptor</code>.
// * @param flowInstanceDescriptor An existing instance of FlowInstanceDescriptor subclass.
// */
// void initialize(FlowInstanceDescriptor flowInstanceDescriptor);
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/instance/session/FlowSession.java
import org.springframework.extensions.workflow.instance.FlowInstance;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer;
package org.springframework.extensions.workflow.instance.session;
/**
* This interface provides methods to interact with the {@link FlowInstance}s.
* Typically, the FlowSession instances will be Spring beans and you will
* call its methods to obtain the <code>FlowInstance</code>s.
* @author janm
*/
public interface FlowSession {
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* This method will not initialize the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
* attached to the <code>FlowDefinition</code>, it will only call its default constructor. To create the descriptor
* yourself, call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator)};
* to perform custom initialization on an instance of the <code>FlowInstanceDescriptor</code>,
* call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer)}
* @param id The identity of the flow, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorCreator.create()</code> to obtain an
* instance of the <code>FlowInstanceDescriptor</code> for this flow instance.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorCreator The implementaiton of the FlowInstanceDescriptorCreator, never <code>null</code>
* @return The FlowInstance at the starting state
*/ | FlowInstance start(String id, FlowInstanceDescriptorCreator instanceDescriptorCreator); |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/instance/session/FlowSession.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstance.java
// public interface FlowInstance extends FlowInstanceDescriptor, FlowInstanceTransitioner {
//
// FlowInstanceDescriptor getFlowInstanceDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorCreator.java
// public interface FlowInstanceDescriptorCreator {
//
// /**
// * Returns a fully constructed and initialized instance of the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
// * @return The FlowInstanceDescriptor instance
// */
// FlowInstanceDescriptor create();
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorInitializer.java
// public interface FlowInstanceDescriptorInitializer {
//
// /**
// * Perform any custom initialization of the <code>flowInstanceDescriptor</code>.
// * @param flowInstanceDescriptor An existing instance of FlowInstanceDescriptor subclass.
// */
// void initialize(FlowInstanceDescriptor flowInstanceDescriptor);
//
// }
| import org.springframework.extensions.workflow.instance.FlowInstance;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer; | package org.springframework.extensions.workflow.instance.session;
/**
* This interface provides methods to interact with the {@link FlowInstance}s.
* Typically, the FlowSession instances will be Spring beans and you will
* call its methods to obtain the <code>FlowInstance</code>s.
* @author janm
*/
public interface FlowSession {
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* This method will not initialize the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
* attached to the <code>FlowDefinition</code>, it will only call its default constructor. To create the descriptor
* yourself, call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator)};
* to perform custom initialization on an instance of the <code>FlowInstanceDescriptor</code>,
* call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer)}
* @param id The identity of the flow, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorCreator.create()</code> to obtain an
* instance of the <code>FlowInstanceDescriptor</code> for this flow instance.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorCreator The implementaiton of the FlowInstanceDescriptorCreator, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id, FlowInstanceDescriptorCreator instanceDescriptorCreator);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorInitialize.initialize(FlowInstanceDescriptor)</code> to
* perform additional initialization of the <code>FlowInstanceDescriptor</code> subclass
* associated with the <code>FlowDefinition</code>.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorInitializer The implementation of the FlowInstanceDescriptorInitializer, never <code>null</code>
* @return The FlowInstance at the starting state
*/ | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstance.java
// public interface FlowInstance extends FlowInstanceDescriptor, FlowInstanceTransitioner {
//
// FlowInstanceDescriptor getFlowInstanceDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorCreator.java
// public interface FlowInstanceDescriptorCreator {
//
// /**
// * Returns a fully constructed and initialized instance of the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
// * @return The FlowInstanceDescriptor instance
// */
// FlowInstanceDescriptor create();
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorInitializer.java
// public interface FlowInstanceDescriptorInitializer {
//
// /**
// * Perform any custom initialization of the <code>flowInstanceDescriptor</code>.
// * @param flowInstanceDescriptor An existing instance of FlowInstanceDescriptor subclass.
// */
// void initialize(FlowInstanceDescriptor flowInstanceDescriptor);
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/instance/session/FlowSession.java
import org.springframework.extensions.workflow.instance.FlowInstance;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer;
package org.springframework.extensions.workflow.instance.session;
/**
* This interface provides methods to interact with the {@link FlowInstance}s.
* Typically, the FlowSession instances will be Spring beans and you will
* call its methods to obtain the <code>FlowInstance</code>s.
* @author janm
*/
public interface FlowSession {
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* This method will not initialize the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
* attached to the <code>FlowDefinition</code>, it will only call its default constructor. To create the descriptor
* yourself, call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator)};
* to perform custom initialization on an instance of the <code>FlowInstanceDescriptor</code>,
* call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer)}
* @param id The identity of the flow, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorCreator.create()</code> to obtain an
* instance of the <code>FlowInstanceDescriptor</code> for this flow instance.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorCreator The implementaiton of the FlowInstanceDescriptorCreator, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id, FlowInstanceDescriptorCreator instanceDescriptorCreator);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorInitialize.initialize(FlowInstanceDescriptor)</code> to
* perform additional initialization of the <code>FlowInstanceDescriptor</code> subclass
* associated with the <code>FlowDefinition</code>.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorInitializer The implementation of the FlowInstanceDescriptorInitializer, never <code>null</code>
* @return The FlowInstance at the starting state
*/ | FlowInstance start(String id, FlowInstanceDescriptorInitializer instanceDescriptorInitializer); |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/instance/session/FlowSession.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstance.java
// public interface FlowInstance extends FlowInstanceDescriptor, FlowInstanceTransitioner {
//
// FlowInstanceDescriptor getFlowInstanceDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorCreator.java
// public interface FlowInstanceDescriptorCreator {
//
// /**
// * Returns a fully constructed and initialized instance of the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
// * @return The FlowInstanceDescriptor instance
// */
// FlowInstanceDescriptor create();
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorInitializer.java
// public interface FlowInstanceDescriptorInitializer {
//
// /**
// * Perform any custom initialization of the <code>flowInstanceDescriptor</code>.
// * @param flowInstanceDescriptor An existing instance of FlowInstanceDescriptor subclass.
// */
// void initialize(FlowInstanceDescriptor flowInstanceDescriptor);
//
// }
| import org.springframework.extensions.workflow.instance.FlowInstance;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer; | package org.springframework.extensions.workflow.instance.session;
/**
* This interface provides methods to interact with the {@link FlowInstance}s.
* Typically, the FlowSession instances will be Spring beans and you will
* call its methods to obtain the <code>FlowInstance</code>s.
* @author janm
*/
public interface FlowSession {
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* This method will not initialize the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
* attached to the <code>FlowDefinition</code>, it will only call its default constructor. To create the descriptor
* yourself, call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator)};
* to perform custom initialization on an instance of the <code>FlowInstanceDescriptor</code>,
* call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer)}
* @param id The identity of the flow, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorCreator.create()</code> to obtain an
* instance of the <code>FlowInstanceDescriptor</code> for this flow instance.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorCreator The implementaiton of the FlowInstanceDescriptorCreator, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id, FlowInstanceDescriptorCreator instanceDescriptorCreator);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorInitialize.initialize(FlowInstanceDescriptor)</code> to
* perform additional initialization of the <code>FlowInstanceDescriptor</code> subclass
* associated with the <code>FlowDefinition</code>.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorInitializer The implementation of the FlowInstanceDescriptorInitializer, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id, FlowInstanceDescriptorInitializer instanceDescriptorInitializer);
/**
* Returns a {@link FlowInstance} for the given {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}.
* This allows you to "step into" the flow -- the <code>FlowInstanceDescriptor</code> carries, amongst other properties,
* the identity of the current state.<br/>
* Typically, you will use this method to get the <code>FlowInstance</code> for
* the <code>FlowInstanceDescriptor</code> you obtained from a database lookup, for instance.
* @param descriptor The FlowInstanceDescriptor instance, never <code>null</code>
* @return The FlowInstance at the appropriate state
*/ | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstance.java
// public interface FlowInstance extends FlowInstanceDescriptor, FlowInstanceTransitioner {
//
// FlowInstanceDescriptor getFlowInstanceDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorCreator.java
// public interface FlowInstanceDescriptorCreator {
//
// /**
// * Returns a fully constructed and initialized instance of the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
// * @return The FlowInstanceDescriptor instance
// */
// FlowInstanceDescriptor create();
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorInitializer.java
// public interface FlowInstanceDescriptorInitializer {
//
// /**
// * Perform any custom initialization of the <code>flowInstanceDescriptor</code>.
// * @param flowInstanceDescriptor An existing instance of FlowInstanceDescriptor subclass.
// */
// void initialize(FlowInstanceDescriptor flowInstanceDescriptor);
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/instance/session/FlowSession.java
import org.springframework.extensions.workflow.instance.FlowInstance;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer;
package org.springframework.extensions.workflow.instance.session;
/**
* This interface provides methods to interact with the {@link FlowInstance}s.
* Typically, the FlowSession instances will be Spring beans and you will
* call its methods to obtain the <code>FlowInstance</code>s.
* @author janm
*/
public interface FlowSession {
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* This method will not initialize the {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}
* attached to the <code>FlowDefinition</code>, it will only call its default constructor. To create the descriptor
* yourself, call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorCreator)};
* to perform custom initialization on an instance of the <code>FlowInstanceDescriptor</code>,
* call {@link #start(String, org.springframework.extensions.workflow.instance.FlowInstanceDescriptorInitializer)}
* @param id The identity of the flow, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorCreator.create()</code> to obtain an
* instance of the <code>FlowInstanceDescriptor</code> for this flow instance.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorCreator The implementaiton of the FlowInstanceDescriptorCreator, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id, FlowInstanceDescriptorCreator instanceDescriptorCreator);
/**
* Starts a flow with the given <code>id</code>. The implementation will find
* a Spring-registred {@link org.springframework.extensions.workflow.FlowDefinition} whose
* <code>id</code> matches the argument. If no such flow is found,
* the method will throw {@link org.springframework.extensions.workflow.NoSuchFlowDefinitionException}.
* The method will call <code>instanceDescriptorInitialize.initialize(FlowInstanceDescriptor)</code> to
* perform additional initialization of the <code>FlowInstanceDescriptor</code> subclass
* associated with the <code>FlowDefinition</code>.
* @param id The identity of the flow, never <code>null</code>
* @param instanceDescriptorInitializer The implementation of the FlowInstanceDescriptorInitializer, never <code>null</code>
* @return The FlowInstance at the starting state
*/
FlowInstance start(String id, FlowInstanceDescriptorInitializer instanceDescriptorInitializer);
/**
* Returns a {@link FlowInstance} for the given {@link org.springframework.extensions.workflow.instance.FlowInstanceDescriptor}.
* This allows you to "step into" the flow -- the <code>FlowInstanceDescriptor</code> carries, amongst other properties,
* the identity of the current state.<br/>
* Typically, you will use this method to get the <code>FlowInstance</code> for
* the <code>FlowInstanceDescriptor</code> you obtained from a database lookup, for instance.
* @param descriptor The FlowInstanceDescriptor instance, never <code>null</code>
* @return The FlowInstance at the appropriate state
*/ | FlowInstance find(FlowInstanceDescriptor descriptor); |
abashev/spring-workflow | src/test/java/org/springframework/extensions/workflow/flow/EndState.java | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
| import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor; | package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(end = true)
public class EndState { | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
// Path: src/test/java/org/springframework/extensions/workflow/flow/EndState.java
import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(end = true)
public class EndState { | private TransitionHolder lastTransition; |
abashev/spring-workflow | src/test/java/org/springframework/extensions/workflow/flow/EndState.java | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
| import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor; | package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(end = true)
public class EndState {
private TransitionHolder lastTransition;
@Transition
@ReturnsState
public String one(String to) { | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
// Path: src/test/java/org/springframework/extensions/workflow/flow/EndState.java
import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(end = true)
public class EndState {
private TransitionHolder lastTransition;
@Transition
@ReturnsState
public String one(String to) { | LongFlowInstanceDescriptor d = getFlowInstanceDescriptor(); |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/support/KnownMethodInvokingTransitionAction.java | // Path: src/main/java/org/springframework/extensions/workflow/TransitionAction.java
// public interface TransitionAction {
//
// void perform(TransitionActionContext actionContext) throws Exception;
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
| import org.springframework.extensions.workflow.TransitionAction;
import org.springframework.extensions.workflow.context.TransitionActionContext;
import java.lang.reflect.Method; | package org.springframework.extensions.workflow.support;
/**
* @author janm
*/
class KnownMethodInvokingTransitionAction implements TransitionAction {
private transient TransitionMethodInvoker transitionMethodInvoker;
public KnownMethodInvokingTransitionAction(Object target, Method method) {
this.transitionMethodInvoker = new TransitionMethodInvoker(target, method);
}
| // Path: src/main/java/org/springframework/extensions/workflow/TransitionAction.java
// public interface TransitionAction {
//
// void perform(TransitionActionContext actionContext) throws Exception;
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
// Path: src/main/java/org/springframework/extensions/workflow/support/KnownMethodInvokingTransitionAction.java
import org.springframework.extensions.workflow.TransitionAction;
import org.springframework.extensions.workflow.context.TransitionActionContext;
import java.lang.reflect.Method;
package org.springframework.extensions.workflow.support;
/**
* @author janm
*/
class KnownMethodInvokingTransitionAction implements TransitionAction {
private transient TransitionMethodInvoker transitionMethodInvoker;
public KnownMethodInvokingTransitionAction(Object target, Method method) {
this.transitionMethodInvoker = new TransitionMethodInvoker(target, method);
}
| public void perform(TransitionActionContext actionContext) throws Exception { |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/support/MethodInvokingTransitionAction.java | // Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/TransitionAction.java
// public interface TransitionAction {
//
// void perform(TransitionActionContext actionContext) throws Exception;
//
// }
| import org.springframework.extensions.workflow.context.TransitionActionContext;
import org.springframework.extensions.workflow.TransitionAction;
import org.springframework.util.Assert; | package org.springframework.extensions.workflow.support;
/**
* @author janm
*/
public class MethodInvokingTransitionAction implements TransitionAction {
private transient TransitionMethodInvoker transitionMethodInvoker;
public MethodInvokingTransitionAction(Object target, String methodName) throws NoSuchMethodException, ClassNotFoundException {
Assert.notNull(target, "The 'target' argument must not be null.");
Assert.notNull(methodName, "The 'methodName' argument must not be null.");
this.transitionMethodInvoker = new TransitionMethodInvoker(target, methodName);
}
| // Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/TransitionAction.java
// public interface TransitionAction {
//
// void perform(TransitionActionContext actionContext) throws Exception;
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/support/MethodInvokingTransitionAction.java
import org.springframework.extensions.workflow.context.TransitionActionContext;
import org.springframework.extensions.workflow.TransitionAction;
import org.springframework.util.Assert;
package org.springframework.extensions.workflow.support;
/**
* @author janm
*/
public class MethodInvokingTransitionAction implements TransitionAction {
private transient TransitionMethodInvoker transitionMethodInvoker;
public MethodInvokingTransitionAction(Object target, String methodName) throws NoSuchMethodException, ClassNotFoundException {
Assert.notNull(target, "The 'target' argument must not be null.");
Assert.notNull(methodName, "The 'methodName' argument must not be null.");
this.transitionMethodInvoker = new TransitionMethodInvoker(target, methodName);
}
| public void perform(TransitionActionContext actionContext) throws Exception { |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
| import org.springframework.util.Assert;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import java.util.HashMap;
import java.util.Map;
import java.io.Serializable; | package org.springframework.extensions.workflow.context;
/**
* @author janm
*/
public final class FlowInstanceDescriptorHolder implements Serializable{
private static final long serialVersionUID = 969547478248429191L;
private static final String STRATEGY_THREADLOCAL = "threadlocal";
private static Map<String, FlowInstanceDescriptorHolderStrategy> strategies;
private static String currentStrategy;
static {
strategies = new HashMap<String, FlowInstanceDescriptorHolderStrategy>();
strategies.put(STRATEGY_THREADLOCAL, new ThreadLocalFlowInstanceDescriptorHolderStrategy());
currentStrategy = STRATEGY_THREADLOCAL;
}
private static FlowInstanceDescriptorHolderStrategy getStrategy() {
return strategies.get(currentStrategy);
}
public static void setStrategy(String strategy) {
Assert.notNull(currentStrategy, "The 'currentStrategy' argument must not be null.");
currentStrategy = strategy;
}
@SuppressWarnings({"unchecked"}) | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
import org.springframework.util.Assert;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import java.util.HashMap;
import java.util.Map;
import java.io.Serializable;
package org.springframework.extensions.workflow.context;
/**
* @author janm
*/
public final class FlowInstanceDescriptorHolder implements Serializable{
private static final long serialVersionUID = 969547478248429191L;
private static final String STRATEGY_THREADLOCAL = "threadlocal";
private static Map<String, FlowInstanceDescriptorHolderStrategy> strategies;
private static String currentStrategy;
static {
strategies = new HashMap<String, FlowInstanceDescriptorHolderStrategy>();
strategies.put(STRATEGY_THREADLOCAL, new ThreadLocalFlowInstanceDescriptorHolderStrategy());
currentStrategy = STRATEGY_THREADLOCAL;
}
private static FlowInstanceDescriptorHolderStrategy getStrategy() {
return strategies.get(currentStrategy);
}
public static void setStrategy(String strategy) {
Assert.notNull(currentStrategy, "The 'currentStrategy' argument must not be null.");
currentStrategy = strategy;
}
@SuppressWarnings({"unchecked"}) | public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() { |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/context/ThreadLocalFlowInstanceDescriptorHolderStrategy.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
| import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor; | package org.springframework.extensions.workflow.context;
/**
* @author janm
*/
public class ThreadLocalFlowInstanceDescriptorHolderStrategy implements FlowInstanceDescriptorHolderStrategy {
private static final long serialVersionUID = 5846317781576476233L; | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
// Path: src/main/java/org/springframework/extensions/workflow/context/ThreadLocalFlowInstanceDescriptorHolderStrategy.java
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
package org.springframework.extensions.workflow.context;
/**
* @author janm
*/
public class ThreadLocalFlowInstanceDescriptorHolderStrategy implements FlowInstanceDescriptorHolderStrategy {
private static final long serialVersionUID = 5846317781576476233L; | private ThreadLocal<FlowInstanceDescriptor> descriptorThreadLocal; |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/support/TransitionMethodInvoker.java | // Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// public final class FlowInstanceDescriptorHolder implements Serializable{
// private static final long serialVersionUID = 969547478248429191L;
// private static final String STRATEGY_THREADLOCAL = "threadlocal";
// private static Map<String, FlowInstanceDescriptorHolderStrategy> strategies;
// private static String currentStrategy;
//
// static {
// strategies = new HashMap<String, FlowInstanceDescriptorHolderStrategy>();
// strategies.put(STRATEGY_THREADLOCAL, new ThreadLocalFlowInstanceDescriptorHolderStrategy());
// currentStrategy = STRATEGY_THREADLOCAL;
// }
//
// private static FlowInstanceDescriptorHolderStrategy getStrategy() {
// return strategies.get(currentStrategy);
// }
//
// public static void setStrategy(String strategy) {
// Assert.notNull(currentStrategy, "The 'currentStrategy' argument must not be null.");
// currentStrategy = strategy;
// }
//
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// public static void setFlowInstanceDescriptor(FlowInstanceDescriptor descriptor) {
// getStrategy().setDescriptor(descriptor);
// }
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
| import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
import static org.springframework.util.Assert.notNull;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.PropertyAccessor;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder;
import org.springframework.extensions.workflow.context.TransitionActionContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | this.target = target;
this.method = method;
prepareCall();
}
TransitionMethodInvoker(Object target, String methodName) {
notNull(target, "The 'target' argument must not be null.");
notNull(methodName, "The 'methodName' argument must not be null.");
this.target = target;
for (Method method : ReflectionUtils.getAllDeclaredMethods(this.target.getClass())) {
if (methodName.equals(method.getName())) {
this.method = method;
break;
}
}
if (this.method == null) {
throw new IllegalArgumentException("Object " + target + " does not define [accessible] method " + methodName);
}
prepareCall();
}
private void prepareCall() {
parameterAnnotations = method.getParameterAnnotations();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
parameterNames = discoverer.getParameterNames(method);
}
| // Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// public final class FlowInstanceDescriptorHolder implements Serializable{
// private static final long serialVersionUID = 969547478248429191L;
// private static final String STRATEGY_THREADLOCAL = "threadlocal";
// private static Map<String, FlowInstanceDescriptorHolderStrategy> strategies;
// private static String currentStrategy;
//
// static {
// strategies = new HashMap<String, FlowInstanceDescriptorHolderStrategy>();
// strategies.put(STRATEGY_THREADLOCAL, new ThreadLocalFlowInstanceDescriptorHolderStrategy());
// currentStrategy = STRATEGY_THREADLOCAL;
// }
//
// private static FlowInstanceDescriptorHolderStrategy getStrategy() {
// return strategies.get(currentStrategy);
// }
//
// public static void setStrategy(String strategy) {
// Assert.notNull(currentStrategy, "The 'currentStrategy' argument must not be null.");
// currentStrategy = strategy;
// }
//
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// public static void setFlowInstanceDescriptor(FlowInstanceDescriptor descriptor) {
// getStrategy().setDescriptor(descriptor);
// }
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
// Path: src/main/java/org/springframework/extensions/workflow/support/TransitionMethodInvoker.java
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
import static org.springframework.util.Assert.notNull;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.PropertyAccessor;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder;
import org.springframework.extensions.workflow.context.TransitionActionContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
this.target = target;
this.method = method;
prepareCall();
}
TransitionMethodInvoker(Object target, String methodName) {
notNull(target, "The 'target' argument must not be null.");
notNull(methodName, "The 'methodName' argument must not be null.");
this.target = target;
for (Method method : ReflectionUtils.getAllDeclaredMethods(this.target.getClass())) {
if (methodName.equals(method.getName())) {
this.method = method;
break;
}
}
if (this.method == null) {
throw new IllegalArgumentException("Object " + target + " does not define [accessible] method " + methodName);
}
prepareCall();
}
private void prepareCall() {
parameterAnnotations = method.getParameterAnnotations();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
parameterNames = discoverer.getParameterNames(method);
}
| Object invoke(TransitionActionContext actionContext) throws IllegalAccessException, InvocationTargetException { |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/support/TransitionMethodInvoker.java | // Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// public final class FlowInstanceDescriptorHolder implements Serializable{
// private static final long serialVersionUID = 969547478248429191L;
// private static final String STRATEGY_THREADLOCAL = "threadlocal";
// private static Map<String, FlowInstanceDescriptorHolderStrategy> strategies;
// private static String currentStrategy;
//
// static {
// strategies = new HashMap<String, FlowInstanceDescriptorHolderStrategy>();
// strategies.put(STRATEGY_THREADLOCAL, new ThreadLocalFlowInstanceDescriptorHolderStrategy());
// currentStrategy = STRATEGY_THREADLOCAL;
// }
//
// private static FlowInstanceDescriptorHolderStrategy getStrategy() {
// return strategies.get(currentStrategy);
// }
//
// public static void setStrategy(String strategy) {
// Assert.notNull(currentStrategy, "The 'currentStrategy' argument must not be null.");
// currentStrategy = strategy;
// }
//
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// public static void setFlowInstanceDescriptor(FlowInstanceDescriptor descriptor) {
// getStrategy().setDescriptor(descriptor);
// }
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
| import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
import static org.springframework.util.Assert.notNull;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.PropertyAccessor;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder;
import org.springframework.extensions.workflow.context.TransitionActionContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | this.method = method;
break;
}
}
if (this.method == null) {
throw new IllegalArgumentException("Object " + target + " does not define [accessible] method " + methodName);
}
prepareCall();
}
private void prepareCall() {
parameterAnnotations = method.getParameterAnnotations();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
parameterNames = discoverer.getParameterNames(method);
}
Object invoke(TransitionActionContext actionContext) throws IllegalAccessException, InvocationTargetException {
List<Object> arguments = new ArrayList<Object>();
int fromContext = 0;
for (int i = 0; i < parameterAnnotations.length; i++) {
Annotation[] parameterAnnotation = parameterAnnotations[i];
boolean fromDescriptor = false;
for (Annotation annotation : parameterAnnotation) {
if (annotation.annotationType().equals(Descriptor.class)) {
fromDescriptor = true;
| // Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// public final class FlowInstanceDescriptorHolder implements Serializable{
// private static final long serialVersionUID = 969547478248429191L;
// private static final String STRATEGY_THREADLOCAL = "threadlocal";
// private static Map<String, FlowInstanceDescriptorHolderStrategy> strategies;
// private static String currentStrategy;
//
// static {
// strategies = new HashMap<String, FlowInstanceDescriptorHolderStrategy>();
// strategies.put(STRATEGY_THREADLOCAL, new ThreadLocalFlowInstanceDescriptorHolderStrategy());
// currentStrategy = STRATEGY_THREADLOCAL;
// }
//
// private static FlowInstanceDescriptorHolderStrategy getStrategy() {
// return strategies.get(currentStrategy);
// }
//
// public static void setStrategy(String strategy) {
// Assert.notNull(currentStrategy, "The 'currentStrategy' argument must not be null.");
// currentStrategy = strategy;
// }
//
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
//
// public static void setFlowInstanceDescriptor(FlowInstanceDescriptor descriptor) {
// getStrategy().setDescriptor(descriptor);
// }
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/TransitionActionContext.java
// public final class TransitionActionContext implements Serializable{
// private static final long serialVersionUID = -2438974871913081078L;
// private String targetStateId;
// private Object[] arguments;
//
// public TransitionActionContext(String targetStateId, Object[] arguments) {
// this.targetStateId = targetStateId;
// this.arguments = arguments;
// }
//
// public Object[] getArguments() {
// return arguments;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
// }
// Path: src/main/java/org/springframework/extensions/workflow/support/TransitionMethodInvoker.java
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
import static org.springframework.util.Assert.notNull;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.PropertyAccessor;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.ReturnsState;
import org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder;
import org.springframework.extensions.workflow.context.TransitionActionContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
this.method = method;
break;
}
}
if (this.method == null) {
throw new IllegalArgumentException("Object " + target + " does not define [accessible] method " + methodName);
}
prepareCall();
}
private void prepareCall() {
parameterAnnotations = method.getParameterAnnotations();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
parameterNames = discoverer.getParameterNames(method);
}
Object invoke(TransitionActionContext actionContext) throws IllegalAccessException, InvocationTargetException {
List<Object> arguments = new ArrayList<Object>();
int fromContext = 0;
for (int i = 0; i < parameterAnnotations.length; i++) {
Annotation[] parameterAnnotation = parameterAnnotations[i];
boolean fromDescriptor = false;
for (Annotation annotation : parameterAnnotation) {
if (annotation.annotationType().equals(Descriptor.class)) {
fromDescriptor = true;
| arguments.add(getFlowInstanceDescriptor()); |
abashev/spring-workflow | src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceTransitioner.java | // Path: src/main/java/org/springframework/extensions/workflow/TransitionDefinition.java
// public final class TransitionDefinition implements Serializable {
// private static final long serialVersionUID = 9015525050536415089L;
// private String id;
// private String targetStateId;
// private TransitionAction transitionAction;
// private String roles;
// private String timeoutExpression;
// private boolean internal;
//
// public TransitionDefinition(String id) {
// this.id = id;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
//
// public TransitionAction getTransitionAction() {
// return transitionAction;
// }
//
// public void setTransitionAction(TransitionAction transitionAction) {
// this.transitionAction = transitionAction;
// }
//
// public String getTimeoutExpression() {
// return timeoutExpression;
// }
//
// public void setTimeoutExpression(String timeoutExpression) {
// this.timeoutExpression = timeoutExpression;
// }
//
// public boolean isInternal() {
// return internal;
// }
//
// public void setInternal(boolean internal) {
// this.internal = internal;
// }
//
// public String getRoles() {
// return roles;
// }
//
// public void setRoles(String roles) {
// this.roles = roles;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("TransitionDefinition");
// sb.append("{id='").append(id).append('\'');
// sb.append(", targetStateId='").append(targetStateId).append('\'');
// sb.append(", transitionAction=").append(transitionAction);
// sb.append('}');
// return sb.toString();
// }
// }
| import org.springframework.extensions.workflow.TransitionDefinition;
import java.util.Set; | package org.springframework.extensions.workflow.instance;
/**
* @author janm
*/
public interface FlowInstanceTransitioner {
void performTransition(String id, Object... arguments);
Set<String> getTransitions();
<T extends FlowInstanceDescriptor> Set<String> getTransitions(final TransitionDefinitionFilter<T> filter);
| // Path: src/main/java/org/springframework/extensions/workflow/TransitionDefinition.java
// public final class TransitionDefinition implements Serializable {
// private static final long serialVersionUID = 9015525050536415089L;
// private String id;
// private String targetStateId;
// private TransitionAction transitionAction;
// private String roles;
// private String timeoutExpression;
// private boolean internal;
//
// public TransitionDefinition(String id) {
// this.id = id;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTargetStateId() {
// return targetStateId;
// }
//
// public void setTargetStateId(String targetStateId) {
// this.targetStateId = targetStateId;
// }
//
// public TransitionAction getTransitionAction() {
// return transitionAction;
// }
//
// public void setTransitionAction(TransitionAction transitionAction) {
// this.transitionAction = transitionAction;
// }
//
// public String getTimeoutExpression() {
// return timeoutExpression;
// }
//
// public void setTimeoutExpression(String timeoutExpression) {
// this.timeoutExpression = timeoutExpression;
// }
//
// public boolean isInternal() {
// return internal;
// }
//
// public void setInternal(boolean internal) {
// this.internal = internal;
// }
//
// public String getRoles() {
// return roles;
// }
//
// public void setRoles(String roles) {
// this.roles = roles;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("TransitionDefinition");
// sb.append("{id='").append(id).append('\'');
// sb.append(", targetStateId='").append(targetStateId).append('\'');
// sb.append(", transitionAction=").append(transitionAction);
// sb.append('}');
// return sb.toString();
// }
// }
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceTransitioner.java
import org.springframework.extensions.workflow.TransitionDefinition;
import java.util.Set;
package org.springframework.extensions.workflow.instance;
/**
* @author janm
*/
public interface FlowInstanceTransitioner {
void performTransition(String id, Object... arguments);
Set<String> getTransitions();
<T extends FlowInstanceDescriptor> Set<String> getTransitions(final TransitionDefinitionFilter<T> filter);
| Set<TransitionDefinition> getTransitionDefinitions(); |
abashev/spring-workflow | src/test/java/org/springframework/extensions/workflow/flow/LongFlowInstanceDescriptorPersister.java | // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorPersister.java
// public interface FlowInstanceDescriptorPersister {
//
// void persist(FlowInstanceDescriptor descriptor);
//
// Iterator<? extends FlowInstanceDescriptor> getDescriptorsWithTimeoutsAndDateInPast();
//
// }
| import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorPersister;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; | package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
public class LongFlowInstanceDescriptorPersister implements FlowInstanceDescriptorPersister {
private LongFlowInstanceDescriptor descriptor;
public LongFlowInstanceDescriptor getDescriptor() {
return descriptor;
}
| // Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptor.java
// public interface FlowInstanceDescriptor {
//
// String getFlowDefinitionId();
//
// String getStateDefinitionId();
//
// void setStateDefinitionId(String stateDefinitionId);
//
// void setFlowDefinitionId(String flowDefinitionId);
//
// void setDateEntered(Date date);
//
// Date getDateEntered();
//
// boolean isWithTimeouts();
//
// void setWithTimeouts(boolean hasTimeouts);
//
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/instance/FlowInstanceDescriptorPersister.java
// public interface FlowInstanceDescriptorPersister {
//
// void persist(FlowInstanceDescriptor descriptor);
//
// Iterator<? extends FlowInstanceDescriptor> getDescriptorsWithTimeoutsAndDateInPast();
//
// }
// Path: src/test/java/org/springframework/extensions/workflow/flow/LongFlowInstanceDescriptorPersister.java
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptor;
import org.springframework.extensions.workflow.instance.FlowInstanceDescriptorPersister;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
public class LongFlowInstanceDescriptorPersister implements FlowInstanceDescriptorPersister {
private LongFlowInstanceDescriptor descriptor;
public LongFlowInstanceDescriptor getDescriptor() {
return descriptor;
}
| public void persist(FlowInstanceDescriptor descriptor) { |
abashev/spring-workflow | src/test/java/org/springframework/extensions/workflow/flow/StartState.java | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
| import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor; | package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(start = true)
public class StartState { | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
// Path: src/test/java/org/springframework/extensions/workflow/flow/StartState.java
import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(start = true)
public class StartState { | private TransitionHolder lastTransition; |
abashev/spring-workflow | src/test/java/org/springframework/extensions/workflow/flow/StartState.java | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
| import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor; | package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(start = true)
public class StartState {
private TransitionHolder lastTransition;
@Transition(roles = "publisher && author")
public void one(@Descriptor LongFlowInstanceDescriptor x, long y) {
x.setSomeValue(y);
this.lastTransition.setLastTransitionId("StartState.one");
}
@Transition(to = "end", timeout = "2s")
public void end(@DescriptorProperty Long someValue) { | // Path: src/test/java/org/springframework/extensions/workflow/TransitionHolder.java
// public class TransitionHolder {
// private String lastTransitionId;
// private Object[] lastTransitionArguments = new Object[0];
//
// public String getLastTransitionId() {
// return lastTransitionId;
// }
//
// public void setLastTransitionId(String lastTransitionId) {
// this.lastTransitionId = lastTransitionId;
// }
//
// public Object[] getLastTransitionArguments() {
// return lastTransitionArguments;
// }
//
// public void setLastTransitionArguments(Object... lastTransitionArguments) {
// this.lastTransitionArguments = lastTransitionArguments;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append(this.lastTransitionId).append("(");
// for (int i = 0; i < this.lastTransitionArguments.length - 1; i++) {
// if (i > 0) sb.append(", ");
// sb.append(this.lastTransitionArguments[i]);
// }
// sb.append(")");
// return sb.toString();
// }
// }
//
// Path: src/main/java/org/springframework/extensions/workflow/context/FlowInstanceDescriptorHolder.java
// @SuppressWarnings({"unchecked"})
// public static <T extends FlowInstanceDescriptor> T getFlowInstanceDescriptor() {
// return (T) getStrategy().getDescriptor();
// }
// Path: src/test/java/org/springframework/extensions/workflow/flow/StartState.java
import org.springframework.extensions.workflow.TransitionHolder;
import org.springframework.extensions.workflow.annotation.Descriptor;
import org.springframework.extensions.workflow.annotation.DescriptorProperty;
import org.springframework.extensions.workflow.annotation.State;
import org.springframework.extensions.workflow.annotation.Transition;
import static org.springframework.extensions.workflow.context.FlowInstanceDescriptorHolder.getFlowInstanceDescriptor;
package org.springframework.extensions.workflow.flow;
/**
* @author janm
*/
@State(start = true)
public class StartState {
private TransitionHolder lastTransition;
@Transition(roles = "publisher && author")
public void one(@Descriptor LongFlowInstanceDescriptor x, long y) {
x.setSomeValue(y);
this.lastTransition.setLastTransitionId("StartState.one");
}
@Transition(to = "end", timeout = "2s")
public void end(@DescriptorProperty Long someValue) { | LongFlowInstanceDescriptor d = getFlowInstanceDescriptor(); |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/Usage.java | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
| import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult; | package com.mailosaur;
public class Usage {
private MailosaurClient client;
public Usage(MailosaurClient client) {
this.client = client;
}
/**
* Retrieve account usage limits. Details the current limits and usage for your account.
* This endpoint requires authentication with an account-level API key.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The current limits and usage for your account.
*/ | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
// Path: src/main/java/com/mailosaur/Usage.java
import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult;
package com.mailosaur;
public class Usage {
private MailosaurClient client;
public Usage(MailosaurClient client) {
this.client = client;
}
/**
* Retrieve account usage limits. Details the current limits and usage for your account.
* This endpoint requires authentication with an account-level API key.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The current limits and usage for your account.
*/ | public UsageAccountLimits limits() throws IOException, MailosaurException { |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/Usage.java | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
| import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult; | package com.mailosaur;
public class Usage {
private MailosaurClient client;
public Usage(MailosaurClient client) {
this.client = client;
}
/**
* Retrieve account usage limits. Details the current limits and usage for your account.
* This endpoint requires authentication with an account-level API key.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The current limits and usage for your account.
*/
public UsageAccountLimits limits() throws IOException, MailosaurException {
return client.request("GET", "api/usage/limits").parseAs(UsageAccountLimits.class);
}
/**
* Retrieves the last 31 days of transactional usage.
* This endpoint requires authentication with an account-level API key.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return Usage transactions from your account.
*/ | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
// Path: src/main/java/com/mailosaur/Usage.java
import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult;
package com.mailosaur;
public class Usage {
private MailosaurClient client;
public Usage(MailosaurClient client) {
this.client = client;
}
/**
* Retrieve account usage limits. Details the current limits and usage for your account.
* This endpoint requires authentication with an account-level API key.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The current limits and usage for your account.
*/
public UsageAccountLimits limits() throws IOException, MailosaurException {
return client.request("GET", "api/usage/limits").parseAs(UsageAccountLimits.class);
}
/**
* Retrieves the last 31 days of transactional usage.
* This endpoint requires authentication with an account-level API key.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return Usage transactions from your account.
*/ | public UsageTransactionListResult transactions() throws IOException, MailosaurException { |
mailosaur/mailosaur-java | src/test/java/com/mailosaur/UsageTest.java | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
| import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult; | package com.mailosaur;
public class UsageTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testLimits() throws IOException, MailosaurException { | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
// Path: src/test/java/com/mailosaur/UsageTest.java
import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult;
package com.mailosaur;
public class UsageTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testLimits() throws IOException, MailosaurException { | UsageAccountLimits result = client.usage().limits(); |
mailosaur/mailosaur-java | src/test/java/com/mailosaur/UsageTest.java | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
| import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult; | package com.mailosaur;
public class UsageTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testLimits() throws IOException, MailosaurException {
UsageAccountLimits result = client.usage().limits();
assertNotNull(result.servers());
assertNotNull(result.users());
assertNotNull(result.email());
assertNotNull(result.sms());
assertTrue(result.servers().limit() > 0);
assertTrue(result.users().limit() > 0);
assertTrue(result.email().limit() > 0);
assertTrue(result.sms().limit() > 0);
}
@Test
public void testTransactions() throws IOException, MailosaurException { | // Path: src/main/java/com/mailosaur/models/UsageAccountLimits.java
// public class UsageAccountLimits {
// /**
// * Server limits.
// */
// @Key
// private UsageAccountLimit servers;
//
// /**
// * User limits.
// */
// @Key
// private UsageAccountLimit users;
//
// /**
// * Emails per day limits.
// */
// @Key
// private UsageAccountLimit email;
//
// /**
// * SMS message per month limits.
// */
// @Key
// private UsageAccountLimit sms;
//
// /**
// * Gets server limits.
// *
// * @return Server limits.
// */
// public UsageAccountLimit servers() {
// return this.servers;
// }
//
// /**
// * Gets user limits.
// *
// * @return User limits.
// */
// public UsageAccountLimit users() {
// return this.users;
// }
//
// /**
// * Gets emails per day limits.
// *
// * @return Emails per day limits.
// */
// public UsageAccountLimit email() {
// return this.email;
// }
//
// /**
// * Gets SMS message per month limits.
// *
// * @return SMS message per month limits.
// */
// public UsageAccountLimit sms() {
// return this.sms;
// }
// }
//
// Path: src/main/java/com/mailosaur/models/UsageTransactionListResult.java
// public class UsageTransactionListResult {
// /**
// * The individual transactions that have occurred.
// */
// @Key
// private List<UsageTransaction> items;
//
// /**
// * Gets the individual transactions that have occurred.
// *
// * @return The individual transactions that have occurred.
// */
// public List<UsageTransaction> items() {
// return this.items;
// }
// }
// Path: src/test/java/com/mailosaur/UsageTest.java
import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.UsageAccountLimits;
import com.mailosaur.models.UsageTransactionListResult;
package com.mailosaur;
public class UsageTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testLimits() throws IOException, MailosaurException {
UsageAccountLimits result = client.usage().limits();
assertNotNull(result.servers());
assertNotNull(result.users());
assertNotNull(result.email());
assertNotNull(result.sms());
assertTrue(result.servers().limit() > 0);
assertTrue(result.users().limit() > 0);
assertTrue(result.email().limit() > 0);
assertTrue(result.sms().limit() > 0);
}
@Test
public void testTransactions() throws IOException, MailosaurException { | UsageTransactionListResult result = client.usage().transactions(); |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/Servers.java | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
| import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult; | package com.mailosaur;
public class Servers {
private MailosaurClient client;
public Servers(MailosaurClient client) {
this.client = client;
}
/**
* Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The result of the server listing operation.
*/ | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
// Path: src/main/java/com/mailosaur/Servers.java
import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult;
package com.mailosaur;
public class Servers {
private MailosaurClient client;
public Servers(MailosaurClient client) {
this.client = client;
}
/**
* Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The result of the server listing operation.
*/ | public ServerListResult list() throws IOException, MailosaurException { |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/Servers.java | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
| import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult; | package com.mailosaur;
public class Servers {
private MailosaurClient client;
public Servers(MailosaurClient client) {
this.client = client;
}
/**
* Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The result of the server listing operation.
*/
public ServerListResult list() throws IOException, MailosaurException {
return client.request("GET", "api/servers").parseAs(ServerListResult.class);
}
/**
* Creates a new virtual server.
*
* @param options Options used to create a new Mailosaur server.
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return Mailosaur virtual SMTP/SMS server.
*/ | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
// Path: src/main/java/com/mailosaur/Servers.java
import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult;
package com.mailosaur;
public class Servers {
private MailosaurClient client;
public Servers(MailosaurClient client) {
this.client = client;
}
/**
* Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The result of the server listing operation.
*/
public ServerListResult list() throws IOException, MailosaurException {
return client.request("GET", "api/servers").parseAs(ServerListResult.class);
}
/**
* Creates a new virtual server.
*
* @param options Options used to create a new Mailosaur server.
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return Mailosaur virtual SMTP/SMS server.
*/ | public Server create(ServerCreateOptions options) throws IOException, MailosaurException { |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/Servers.java | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
| import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult; | package com.mailosaur;
public class Servers {
private MailosaurClient client;
public Servers(MailosaurClient client) {
this.client = client;
}
/**
* Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The result of the server listing operation.
*/
public ServerListResult list() throws IOException, MailosaurException {
return client.request("GET", "api/servers").parseAs(ServerListResult.class);
}
/**
* Creates a new virtual server.
*
* @param options Options used to create a new Mailosaur server.
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return Mailosaur virtual SMTP/SMS server.
*/ | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
// Path: src/main/java/com/mailosaur/Servers.java
import java.io.IOException;
import java.util.Random;
import com.google.api.client.json.GenericJson;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult;
package com.mailosaur;
public class Servers {
private MailosaurClient client;
public Servers(MailosaurClient client) {
this.client = client;
}
/**
* Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.
*
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The result of the server listing operation.
*/
public ServerListResult list() throws IOException, MailosaurException {
return client.request("GET", "api/servers").parseAs(ServerListResult.class);
}
/**
* Creates a new virtual server.
*
* @param options Options used to create a new Mailosaur server.
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return Mailosaur virtual SMTP/SMS server.
*/ | public Server create(ServerCreateOptions options) throws IOException, MailosaurException { |
mailosaur/mailosaur-java | src/test/java/com/mailosaur/ServersTest.java | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
| import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult; | package com.mailosaur;
public class ServersTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testList() throws IOException, MailosaurException { | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
// Path: src/test/java/com/mailosaur/ServersTest.java
import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult;
package com.mailosaur;
public class ServersTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testList() throws IOException, MailosaurException { | ServerListResult servers = client.servers().list(); |
mailosaur/mailosaur-java | src/test/java/com/mailosaur/ServersTest.java | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
| import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult; | package com.mailosaur;
public class ServersTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testList() throws IOException, MailosaurException {
ServerListResult servers = client.servers().list();
assertTrue(servers.items().size() > 1);
}
@Test(expected = MailosaurException.class)
public void testGetNotFound() throws IOException, MailosaurException {
client.servers().get("efe907e9-74ed-4113-a3e0-a3d41d914765");
}
@Test
public void testCrud() throws IOException, MailosaurException {
String serverName = "My test";
// Create a new server | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
// Path: src/test/java/com/mailosaur/ServersTest.java
import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult;
package com.mailosaur;
public class ServersTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testList() throws IOException, MailosaurException {
ServerListResult servers = client.servers().list();
assertTrue(servers.items().size() > 1);
}
@Test(expected = MailosaurException.class)
public void testGetNotFound() throws IOException, MailosaurException {
client.servers().get("efe907e9-74ed-4113-a3e0-a3d41d914765");
}
@Test
public void testCrud() throws IOException, MailosaurException {
String serverName = "My test";
// Create a new server | ServerCreateOptions options = new ServerCreateOptions().withName(serverName); |
mailosaur/mailosaur-java | src/test/java/com/mailosaur/ServersTest.java | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
| import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult; | package com.mailosaur;
public class ServersTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testList() throws IOException, MailosaurException {
ServerListResult servers = client.servers().list();
assertTrue(servers.items().size() > 1);
}
@Test(expected = MailosaurException.class)
public void testGetNotFound() throws IOException, MailosaurException {
client.servers().get("efe907e9-74ed-4113-a3e0-a3d41d914765");
}
@Test
public void testCrud() throws IOException, MailosaurException {
String serverName = "My test";
// Create a new server
ServerCreateOptions options = new ServerCreateOptions().withName(serverName); | // Path: src/main/java/com/mailosaur/models/Server.java
// public class Server {
// /**
// * Unique identifier for the server.
// */
// @Key
// private String id;
//
// /**
// * The name of the server.
// */
// @Key
// private String name;
//
// /**
// * Users (excluding administrators) who have access to the server (if it is restricted).
// */
// @Key
// private List<String> users;
//
// /**
// * The number of messages currently in the server.
// */
// @Key
// private Integer messages;
//
// /**
// * Gets the unique identifier of the server.
// *
// * @return The server ID.
// */
// public String id() {
// return this.id;
// }
//
// /**
// * Gets the name of the server.
// *
// * @return The name of the server.
// */
// public String name() {
// return this.name;
// }
//
// /**
// * Sets the name of the server.
// *
// * @param name The name of the server.
// * @return the Server object itself.
// */
// public Server withName(String name) {
// this.name = name;
// return this;
// }
//
// /**
// * Gets the IDs of users who have access to the server (if it is restricted).
// *
// * @return The IDs of users who have access to the server (if it is restricted).
// */
// public List<String> users() {
// return this.users;
// }
//
// /**
// * Sets the IDs of users who have access to the server (if it is restricted).
// *
// * @param users The IDs of users who have access to the server (if it is restricted).
// * @return the Server object itself.
// */
// public Server withUsers(List<String> users) {
// this.users = users;
// return this;
// }
//
// /**
// * Gets the number of messages currently in the server.
// *
// * @return The number of messages currently in the server.
// */
// public Integer messages() {
// return this.messages;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerCreateOptions.java
// public class ServerCreateOptions {
// /**
// * A name used to identify the server.
// */
// @Key
// private String name;
//
// /**
// * Sets a name used to identify the server.
// *
// * @param name A name used to identify the server.
// * @return the ServerCreateOptions object itself.
// */
// public ServerCreateOptions withName(String name) {
// this.name = name;
// return this;
// }
//
// }
//
// Path: src/main/java/com/mailosaur/models/ServerListResult.java
// public class ServerListResult {
// /**
// * The individual servers forming the result. Servers
// * are returned sorted by creation date, with the most recently-created server
// * appearing first.
// */
// @Key
// private List<Server> items;
//
// /**
// * Gets the individual servers forming the result.
// *
// * @return The individual servers forming the result.
// */
// public List<Server> items() {
// return this.items;
// }
// }
// Path: src/test/java/com/mailosaur/ServersTest.java
import static org.junit.Assert.*;
import java.io.IOException;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mailosaur.models.Server;
import com.mailosaur.models.ServerCreateOptions;
import com.mailosaur.models.ServerListResult;
package com.mailosaur;
public class ServersTest {
private static MailosaurClient client;
@BeforeClass
public static void setUpBeforeClass() throws IOException, InterruptedException, MessagingException {
String apiKey = System.getenv("MAILOSAUR_API_KEY");
String baseUrl = System.getenv("MAILOSAUR_BASE_URL");
if (apiKey == null) {
throw new IOException("Missing necessary environment variables - refer to README.md");
}
client = new MailosaurClient(apiKey, baseUrl);
}
@Test
public void testList() throws IOException, MailosaurException {
ServerListResult servers = client.servers().list();
assertTrue(servers.items().size() > 1);
}
@Test(expected = MailosaurException.class)
public void testGetNotFound() throws IOException, MailosaurException {
client.servers().get("efe907e9-74ed-4113-a3e0-a3d41d914765");
}
@Test
public void testCrud() throws IOException, MailosaurException {
String serverName = "My test";
// Create a new server
ServerCreateOptions options = new ServerCreateOptions().withName(serverName); | Server createdServer = client.servers().create(options); |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/Analysis.java | // Path: src/main/java/com/mailosaur/models/SpamAnalysisResult.java
// public class SpamAnalysisResult {
// /**
// * Spam filter results.
// */
// @Key
// private SpamFilterResults spamFilterResults;
//
// /**
// * Overall Mailosaur spam score.
// */
// @Key
// private Double score;
//
// /**
// * Gets the Spam filter results.
// *
// * @return Spam filter results.
// */
// public SpamFilterResults spamFilterResults() {
// return this.spamFilterResults;
// }
//
// /**
// * Gets the overall Mailosaur spam score.
// *
// * @return The overall Mailosaur spam score.
// */
// public Double score() {
// return this.score;
// }
//
// }
| import java.io.IOException;
import com.mailosaur.models.SpamAnalysisResult; | package com.mailosaur;
/**
* Message analysis operations.
*/
public class Analysis {
private MailosaurClient client;
public Analysis(MailosaurClient client) {
this.client = client;
}
/**
* Perform a spam analysis of an email.
*
* @param messageId The identifier of the message to be analyzed.
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The results of spam analysis performed by Mailosaur.
*/ | // Path: src/main/java/com/mailosaur/models/SpamAnalysisResult.java
// public class SpamAnalysisResult {
// /**
// * Spam filter results.
// */
// @Key
// private SpamFilterResults spamFilterResults;
//
// /**
// * Overall Mailosaur spam score.
// */
// @Key
// private Double score;
//
// /**
// * Gets the Spam filter results.
// *
// * @return Spam filter results.
// */
// public SpamFilterResults spamFilterResults() {
// return this.spamFilterResults;
// }
//
// /**
// * Gets the overall Mailosaur spam score.
// *
// * @return The overall Mailosaur spam score.
// */
// public Double score() {
// return this.score;
// }
//
// }
// Path: src/main/java/com/mailosaur/Analysis.java
import java.io.IOException;
import com.mailosaur.models.SpamAnalysisResult;
package com.mailosaur;
/**
* Message analysis operations.
*/
public class Analysis {
private MailosaurClient client;
public Analysis(MailosaurClient client) {
this.client = client;
}
/**
* Perform a spam analysis of an email.
*
* @param messageId The identifier of the message to be analyzed.
* @throws MailosaurException Thrown if Mailosaur responds with an error.
* @throws IOException Unexpected exception.
* @return The results of spam analysis performed by Mailosaur.
*/ | public SpamAnalysisResult spam(String messageId) throws IOException, MailosaurException { |
damingerdai/web-qq | src/main/java/org/aming/web/qq/domain/Message.java | // Path: src/main/java/org/aming/web/qq/utils/IdGen.java
// public class IdGen {
//
// private static final SecureRandom random = new SecureRandom();
//
// public static String uuid(){
// return UUID.randomUUID().toString().replace("-","");
// }
// }
| import org.aming.web.qq.utils.IdGen;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date; |
public Timestamp getSendDate() {
return sendDate;
}
public Message setSendDate(Timestamp sendDate) {
this.sendDate = sendDate;
return this;
}
public int getSendDeleteFlag() {
return sendDeleteFlag;
}
public Message setSendDeleteFlag(int sendDeleteFlag) {
this.sendDeleteFlag = sendDeleteFlag;
return this;
}
public int getReceiveDeleteFlag() {
return receiveDeleteFlag;
}
public Message setReceiveDeleteFlag(int receiveDeleteFlag) {
this.receiveDeleteFlag = receiveDeleteFlag;
return this;
}
public Message() {
super(); | // Path: src/main/java/org/aming/web/qq/utils/IdGen.java
// public class IdGen {
//
// private static final SecureRandom random = new SecureRandom();
//
// public static String uuid(){
// return UUID.randomUUID().toString().replace("-","");
// }
// }
// Path: src/main/java/org/aming/web/qq/domain/Message.java
import org.aming.web.qq.utils.IdGen;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
public Timestamp getSendDate() {
return sendDate;
}
public Message setSendDate(Timestamp sendDate) {
this.sendDate = sendDate;
return this;
}
public int getSendDeleteFlag() {
return sendDeleteFlag;
}
public Message setSendDeleteFlag(int sendDeleteFlag) {
this.sendDeleteFlag = sendDeleteFlag;
return this;
}
public int getReceiveDeleteFlag() {
return receiveDeleteFlag;
}
public Message setReceiveDeleteFlag(int receiveDeleteFlag) {
this.receiveDeleteFlag = receiveDeleteFlag;
return this;
}
public Message() {
super(); | this.id = IdGen.uuid(); |
damingerdai/web-qq | src/main/java/org/aming/web/qq/repository/jdbc/UserDao.java | // Path: src/main/java/org/aming/web/qq/domain/Relationship.java
// public class Relationship implements Serializable {
// private int id;
// private String userId1;
// private String userId2;
//
// public int getId() {
// return id;
// }
//
// public Relationship setId(int id) {
// this.id = id;
// return this;
// }
//
// public String getUserId1() {
// return userId1;
// }
//
// public Relationship setUserId1(String userId1) {
// this.userId1 = userId1;
// return this;
// }
//
// public String getUserId2() {
// return userId2;
// }
//
// public Relationship setUserId2(String userId2) {
// this.userId2 = userId2;
// return this;
// }
//
// public Relationship(){
// super();
// }
//
// public Relationship(String userId1,String userId2){
// super();
// this.userId1 = userId1;
// this.userId2 = userId2;
// }
//
// public Relationship(int id,String userId1,String userId2){
// super();
// this.id = id;
// this.userId1 = userId1;
// this.userId2 = userId2;
// }
//
// @Override
// public String toString(){
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Relationship reverse(){
// return new Relationship(this.userId2,this.userId1);
// }
//
//
// }
//
// Path: src/main/java/org/aming/web/qq/domain/User.java
// public class User extends AbstractUserDetails implements UserDetails {
//
// private static final long serialVersionUID = -5509256807259591938L;
//
// private String id;
// private String username;
// private String password;
// private String email;
//
// public String getId() {
// return id;
// }
//
// public User setId(String id) {
// this.id = id;
// return this;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public User setUsername(String username) {
// this.username = username;
// return this;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public User setPassword(String password) {
// this.password = password;
// return this;
// }
//
// public String getEmail() {
// return email;
// }
//
// public User setEmail(String email) {
// this.email = email;
// return this;
// }
//
// public User(String id, String username, String password, String email) {
// super();
// this.id = id;
// this.username = username;
// this.password = password;
// this.email = email;
// }
//
// public User(String username, String password) {
// super();
// this.id = IdGen.uuid();
// this.username = username;
// this.password = password;
// }
//
// public User(UserDetails userDetails){
// this(userDetails.getUsername(),userDetails.getPassword());
// }
//
// public User() {
// super();
// this.id = IdGen.uuid();
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// @Override
// public int hashCode() {
// return this.username.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null){
// return false;
// }
// if(obj == this){
// return true;
// }
// if(obj instanceof User){
// if(obj instanceof UserDetails){
// UserDetails userDetails = (UserDetails)obj;
// if(this.getUsername().equals(userDetails.getUsername())){
// return true;
// }
// }else{
// User user = (User)obj;
// if(this.getUsername().equals(user.getUsername())){
// return true;
// }
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/org/aming/web/qq/exceptions/WebQQDaoException.java
// public class WebQQDaoException extends RuntimeException {
//
// private static final long serialVersionUID = -6938498189136673933L;
//
// private String errorSql;
// private Throwable cause;
//
// public String getMessage() {
// return "fail to execute sql : " + this.errorSql;
// }
//
// @Override
// public Throwable getCause() {
// return cause;
// }
//
// public WebQQDaoException(String errorSql) {
// super();
// this.errorSql = errorSql;
// }
//
// public WebQQDaoException(String errorSql, Throwable cause) {
// super();
// this.errorSql = errorSql;
// this.cause = cause;
// }
// }
| import org.aming.web.qq.domain.Relationship;
import org.aming.web.qq.domain.User;
import org.aming.web.qq.exceptions.WebQQDaoException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.List; | package org.aming.web.qq.repository.jdbc;
/**
* @author daming
* @version 2017/10/1.
*/
public interface UserDao {
User loadUserByUsername(String username) throws WebQQDaoException;
List<User> getFriendsByUsername(String username) throws WebQQDaoException;
List<User> findMoreUser(String condition) throws WebQQDaoException;
| // Path: src/main/java/org/aming/web/qq/domain/Relationship.java
// public class Relationship implements Serializable {
// private int id;
// private String userId1;
// private String userId2;
//
// public int getId() {
// return id;
// }
//
// public Relationship setId(int id) {
// this.id = id;
// return this;
// }
//
// public String getUserId1() {
// return userId1;
// }
//
// public Relationship setUserId1(String userId1) {
// this.userId1 = userId1;
// return this;
// }
//
// public String getUserId2() {
// return userId2;
// }
//
// public Relationship setUserId2(String userId2) {
// this.userId2 = userId2;
// return this;
// }
//
// public Relationship(){
// super();
// }
//
// public Relationship(String userId1,String userId2){
// super();
// this.userId1 = userId1;
// this.userId2 = userId2;
// }
//
// public Relationship(int id,String userId1,String userId2){
// super();
// this.id = id;
// this.userId1 = userId1;
// this.userId2 = userId2;
// }
//
// @Override
// public String toString(){
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Relationship reverse(){
// return new Relationship(this.userId2,this.userId1);
// }
//
//
// }
//
// Path: src/main/java/org/aming/web/qq/domain/User.java
// public class User extends AbstractUserDetails implements UserDetails {
//
// private static final long serialVersionUID = -5509256807259591938L;
//
// private String id;
// private String username;
// private String password;
// private String email;
//
// public String getId() {
// return id;
// }
//
// public User setId(String id) {
// this.id = id;
// return this;
// }
//
// @Override
// public String getUsername() {
// return username;
// }
//
// public User setUsername(String username) {
// this.username = username;
// return this;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
//
// public User setPassword(String password) {
// this.password = password;
// return this;
// }
//
// public String getEmail() {
// return email;
// }
//
// public User setEmail(String email) {
// this.email = email;
// return this;
// }
//
// public User(String id, String username, String password, String email) {
// super();
// this.id = id;
// this.username = username;
// this.password = password;
// this.email = email;
// }
//
// public User(String username, String password) {
// super();
// this.id = IdGen.uuid();
// this.username = username;
// this.password = password;
// }
//
// public User(UserDetails userDetails){
// this(userDetails.getUsername(),userDetails.getPassword());
// }
//
// public User() {
// super();
// this.id = IdGen.uuid();
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// @Override
// public int hashCode() {
// return this.username.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj == null){
// return false;
// }
// if(obj == this){
// return true;
// }
// if(obj instanceof User){
// if(obj instanceof UserDetails){
// UserDetails userDetails = (UserDetails)obj;
// if(this.getUsername().equals(userDetails.getUsername())){
// return true;
// }
// }else{
// User user = (User)obj;
// if(this.getUsername().equals(user.getUsername())){
// return true;
// }
// }
// }
// return false;
// }
// }
//
// Path: src/main/java/org/aming/web/qq/exceptions/WebQQDaoException.java
// public class WebQQDaoException extends RuntimeException {
//
// private static final long serialVersionUID = -6938498189136673933L;
//
// private String errorSql;
// private Throwable cause;
//
// public String getMessage() {
// return "fail to execute sql : " + this.errorSql;
// }
//
// @Override
// public Throwable getCause() {
// return cause;
// }
//
// public WebQQDaoException(String errorSql) {
// super();
// this.errorSql = errorSql;
// }
//
// public WebQQDaoException(String errorSql, Throwable cause) {
// super();
// this.errorSql = errorSql;
// this.cause = cause;
// }
// }
// Path: src/main/java/org/aming/web/qq/repository/jdbc/UserDao.java
import org.aming.web.qq.domain.Relationship;
import org.aming.web.qq.domain.User;
import org.aming.web.qq.exceptions.WebQQDaoException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.List;
package org.aming.web.qq.repository.jdbc;
/**
* @author daming
* @version 2017/10/1.
*/
public interface UserDao {
User loadUserByUsername(String username) throws WebQQDaoException;
List<User> getFriendsByUsername(String username) throws WebQQDaoException;
List<User> findMoreUser(String condition) throws WebQQDaoException;
| int saveRelationship(Relationship relationship) throws WebQQDaoException; |
damingerdai/web-qq | src/main/java/org/aming/web/qq/domain/User.java | // Path: src/main/java/org/aming/web/qq/utils/IdGen.java
// public class IdGen {
//
// private static final SecureRandom random = new SecureRandom();
//
// public static String uuid(){
// return UUID.randomUUID().toString().replace("-","");
// }
// }
| import org.aming.web.qq.utils.IdGen;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection; |
@Override
public String getPassword() {
return password;
}
public User setPassword(String password) {
this.password = password;
return this;
}
public String getEmail() {
return email;
}
public User setEmail(String email) {
this.email = email;
return this;
}
public User(String id, String username, String password, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public User(String username, String password) {
super(); | // Path: src/main/java/org/aming/web/qq/utils/IdGen.java
// public class IdGen {
//
// private static final SecureRandom random = new SecureRandom();
//
// public static String uuid(){
// return UUID.randomUUID().toString().replace("-","");
// }
// }
// Path: src/main/java/org/aming/web/qq/domain/User.java
import org.aming.web.qq.utils.IdGen;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
@Override
public String getPassword() {
return password;
}
public User setPassword(String password) {
this.password = password;
return this;
}
public String getEmail() {
return email;
}
public User setEmail(String email) {
this.email = email;
return this;
}
public User(String id, String username, String password, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public User(String username, String password) {
super(); | this.id = IdGen.uuid(); |
damingerdai/web-qq | src/main/java/org/aming/web/qq/response/CommonResponse.java | // Path: src/main/java/org/aming/web/qq/exceptions/WebQQException.java
// public class WebQQException extends RuntimeException {
//
// private static final long serialVersionUID = 7398282580857507024L;
//
// private static final int DEFAULT_CODE = 5000;
// private static final String DEFAULT_MESSAGE = "系统内部错误";
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public WebQQException setCode(int code) {
// this.code = code;
// return this;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQException setMessage(String message) {
// this.message = message;
// return this;
// }
//
//
// public WebQQException(){
// super();
// this.code = DEFAULT_CODE;
// this.message = DEFAULT_MESSAGE;
// }
//
// public WebQQException(Throwable cause){
// super();
// this.code = DEFAULT_CODE;
// this.message = cause.getMessage();
// }
//
// public WebQQException(int code, String message) {
// super();
// this.code = code;
// this.message = message;
// }
//
// }
//
// Path: src/main/java/org/aming/web/qq/exceptions/WebQQServiceException.java
// public class WebQQServiceException extends RuntimeException{
//
// private static final long serialVersionUID = -7873850467298337213L;
//
// private String message;
// private WebQQDaoException cause;
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQServiceException setMessage(String message) {
// this.message = message;
// return this;
// }
//
// @Override
// public WebQQDaoException getCause() {
// return cause;
// }
//
// public WebQQServiceException setCause(WebQQDaoException cause) {
// this.cause = cause;
// return this;
// }
//
// public WebQQServiceException() {
// super();
// }
//
// public WebQQServiceException(String message) {
// super();
// this.message = message;
// }
//
// public WebQQServiceException(String message, WebQQDaoException cause) {
// super();
// this.message = message;
// this.cause = cause;
// }
// }
| import org.aming.web.qq.exceptions.WebQQException;
import org.aming.web.qq.exceptions.WebQQServiceException;
import java.io.Serializable; | package org.aming.web.qq.response;
/**
* @author daming
* @version 2017/10/3.
*/
public class CommonResponse implements Serializable {
private static final long serialVersionUID = 7980325592134636957L;
private static final boolean DEFAULT_SUCCESS_FLAG = true;
private boolean success;
private Object data; | // Path: src/main/java/org/aming/web/qq/exceptions/WebQQException.java
// public class WebQQException extends RuntimeException {
//
// private static final long serialVersionUID = 7398282580857507024L;
//
// private static final int DEFAULT_CODE = 5000;
// private static final String DEFAULT_MESSAGE = "系统内部错误";
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public WebQQException setCode(int code) {
// this.code = code;
// return this;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQException setMessage(String message) {
// this.message = message;
// return this;
// }
//
//
// public WebQQException(){
// super();
// this.code = DEFAULT_CODE;
// this.message = DEFAULT_MESSAGE;
// }
//
// public WebQQException(Throwable cause){
// super();
// this.code = DEFAULT_CODE;
// this.message = cause.getMessage();
// }
//
// public WebQQException(int code, String message) {
// super();
// this.code = code;
// this.message = message;
// }
//
// }
//
// Path: src/main/java/org/aming/web/qq/exceptions/WebQQServiceException.java
// public class WebQQServiceException extends RuntimeException{
//
// private static final long serialVersionUID = -7873850467298337213L;
//
// private String message;
// private WebQQDaoException cause;
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQServiceException setMessage(String message) {
// this.message = message;
// return this;
// }
//
// @Override
// public WebQQDaoException getCause() {
// return cause;
// }
//
// public WebQQServiceException setCause(WebQQDaoException cause) {
// this.cause = cause;
// return this;
// }
//
// public WebQQServiceException() {
// super();
// }
//
// public WebQQServiceException(String message) {
// super();
// this.message = message;
// }
//
// public WebQQServiceException(String message, WebQQDaoException cause) {
// super();
// this.message = message;
// this.cause = cause;
// }
// }
// Path: src/main/java/org/aming/web/qq/response/CommonResponse.java
import org.aming.web.qq.exceptions.WebQQException;
import org.aming.web.qq.exceptions.WebQQServiceException;
import java.io.Serializable;
package org.aming.web.qq.response;
/**
* @author daming
* @version 2017/10/3.
*/
public class CommonResponse implements Serializable {
private static final long serialVersionUID = 7980325592134636957L;
private static final boolean DEFAULT_SUCCESS_FLAG = true;
private boolean success;
private Object data; | private WebQQException error; |
damingerdai/web-qq | src/main/java/org/aming/web/qq/response/CommonResponse.java | // Path: src/main/java/org/aming/web/qq/exceptions/WebQQException.java
// public class WebQQException extends RuntimeException {
//
// private static final long serialVersionUID = 7398282580857507024L;
//
// private static final int DEFAULT_CODE = 5000;
// private static final String DEFAULT_MESSAGE = "系统内部错误";
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public WebQQException setCode(int code) {
// this.code = code;
// return this;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQException setMessage(String message) {
// this.message = message;
// return this;
// }
//
//
// public WebQQException(){
// super();
// this.code = DEFAULT_CODE;
// this.message = DEFAULT_MESSAGE;
// }
//
// public WebQQException(Throwable cause){
// super();
// this.code = DEFAULT_CODE;
// this.message = cause.getMessage();
// }
//
// public WebQQException(int code, String message) {
// super();
// this.code = code;
// this.message = message;
// }
//
// }
//
// Path: src/main/java/org/aming/web/qq/exceptions/WebQQServiceException.java
// public class WebQQServiceException extends RuntimeException{
//
// private static final long serialVersionUID = -7873850467298337213L;
//
// private String message;
// private WebQQDaoException cause;
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQServiceException setMessage(String message) {
// this.message = message;
// return this;
// }
//
// @Override
// public WebQQDaoException getCause() {
// return cause;
// }
//
// public WebQQServiceException setCause(WebQQDaoException cause) {
// this.cause = cause;
// return this;
// }
//
// public WebQQServiceException() {
// super();
// }
//
// public WebQQServiceException(String message) {
// super();
// this.message = message;
// }
//
// public WebQQServiceException(String message, WebQQDaoException cause) {
// super();
// this.message = message;
// this.cause = cause;
// }
// }
| import org.aming.web.qq.exceptions.WebQQException;
import org.aming.web.qq.exceptions.WebQQServiceException;
import java.io.Serializable; | package org.aming.web.qq.response;
/**
* @author daming
* @version 2017/10/3.
*/
public class CommonResponse implements Serializable {
private static final long serialVersionUID = 7980325592134636957L;
private static final boolean DEFAULT_SUCCESS_FLAG = true;
private boolean success;
private Object data;
private WebQQException error;
@Deprecated
public static CommonResponse getCommonResponse(boolean success,Object data){
return new CommonResponse(success,data);
}
public static CommonResponse getSuccessCommonResponse(Object data){
return new CommonResponse(true,data);
}
public static WebQQException getErrorCommonResponse(Throwable error) {
if(error instanceof WebQQException){
return (WebQQException)error; | // Path: src/main/java/org/aming/web/qq/exceptions/WebQQException.java
// public class WebQQException extends RuntimeException {
//
// private static final long serialVersionUID = 7398282580857507024L;
//
// private static final int DEFAULT_CODE = 5000;
// private static final String DEFAULT_MESSAGE = "系统内部错误";
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
// public WebQQException setCode(int code) {
// this.code = code;
// return this;
// }
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQException setMessage(String message) {
// this.message = message;
// return this;
// }
//
//
// public WebQQException(){
// super();
// this.code = DEFAULT_CODE;
// this.message = DEFAULT_MESSAGE;
// }
//
// public WebQQException(Throwable cause){
// super();
// this.code = DEFAULT_CODE;
// this.message = cause.getMessage();
// }
//
// public WebQQException(int code, String message) {
// super();
// this.code = code;
// this.message = message;
// }
//
// }
//
// Path: src/main/java/org/aming/web/qq/exceptions/WebQQServiceException.java
// public class WebQQServiceException extends RuntimeException{
//
// private static final long serialVersionUID = -7873850467298337213L;
//
// private String message;
// private WebQQDaoException cause;
//
// @Override
// public String getMessage() {
// return message;
// }
//
// public WebQQServiceException setMessage(String message) {
// this.message = message;
// return this;
// }
//
// @Override
// public WebQQDaoException getCause() {
// return cause;
// }
//
// public WebQQServiceException setCause(WebQQDaoException cause) {
// this.cause = cause;
// return this;
// }
//
// public WebQQServiceException() {
// super();
// }
//
// public WebQQServiceException(String message) {
// super();
// this.message = message;
// }
//
// public WebQQServiceException(String message, WebQQDaoException cause) {
// super();
// this.message = message;
// this.cause = cause;
// }
// }
// Path: src/main/java/org/aming/web/qq/response/CommonResponse.java
import org.aming.web.qq.exceptions.WebQQException;
import org.aming.web.qq.exceptions.WebQQServiceException;
import java.io.Serializable;
package org.aming.web.qq.response;
/**
* @author daming
* @version 2017/10/3.
*/
public class CommonResponse implements Serializable {
private static final long serialVersionUID = 7980325592134636957L;
private static final boolean DEFAULT_SUCCESS_FLAG = true;
private boolean success;
private Object data;
private WebQQException error;
@Deprecated
public static CommonResponse getCommonResponse(boolean success,Object data){
return new CommonResponse(success,data);
}
public static CommonResponse getSuccessCommonResponse(Object data){
return new CommonResponse(true,data);
}
public static WebQQException getErrorCommonResponse(Throwable error) {
if(error instanceof WebQQException){
return (WebQQException)error; | } else if (error instanceof WebQQServiceException) { |
Netflix/Nicobar | nicobar-core/nicobar-test-classes/dependent-module/src/main/java/com/netflix/nicobar/test/Dependent.java | // Path: nicobar-core/src/test/java/com/netflix/nicobar/test/Service.java
// public class Service {
// public String service() {
// return "From App Classpath";
// }
// }
| import com.netflix.nicobar.test.Service; | package com.netflix.nicobar.test;
public class Dependent {
public static String execute() { | // Path: nicobar-core/src/test/java/com/netflix/nicobar/test/Service.java
// public class Service {
// public String service() {
// return "From App Classpath";
// }
// }
// Path: nicobar-core/nicobar-test-classes/dependent-module/src/main/java/com/netflix/nicobar/test/Dependent.java
import com.netflix.nicobar.test.Service;
package com.netflix.nicobar.test;
public class Dependent {
public static String execute() { | String result = new Service().service(); |
Netflix/Nicobar | nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/TestCompilerPlugin.java | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
// public interface ScriptArchiveCompiler {
// /**
// * Whether or not this compiler should be used to compile the archive
// */
// public boolean shouldCompile(ScriptArchive archive);
//
// /**
// * Compile the archive into a ScriptModule
// * @param archive archive to generate class files for
// * @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
// * The resultant classes of the compile operation should be injected into the classloader
// * for which the given archive has a declared dependency on
// * @param targetDir a directory in which to store compiled classes, if any.
// * @return The set of classes that were compiled
// * @throws ScriptCompilationException if there was a compilation issue in the archive.
// * @throws IOException if there was a problem reading/writing the archive
// */
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException;
// }
//
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/NoOpCompiler.java
// public class NoOpCompiler implements ScriptArchiveCompiler {
//
// @Override
// public boolean shouldCompile(ScriptArchive archive) {
// return true;
// }
//
// @Override
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) {
// return Collections.<Class<?>>emptySet();
// }
// }
| import java.util.Collections;
import java.util.Map;
import java.util.Set;
import com.netflix.nicobar.core.compile.ScriptArchiveCompiler;
import com.netflix.nicobar.core.internal.compile.NoOpCompiler; | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.nicobar.core.plugin;
/**
* A {@link ScriptCompilerPlugin} for script archives with a no-op compiler included.
* Intended for use during testing.
*
* @author Vasanth Asokan
*/
public class TestCompilerPlugin implements ScriptCompilerPlugin {
public static final String PLUGIN_ID = "nolang";
@Override | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
// public interface ScriptArchiveCompiler {
// /**
// * Whether or not this compiler should be used to compile the archive
// */
// public boolean shouldCompile(ScriptArchive archive);
//
// /**
// * Compile the archive into a ScriptModule
// * @param archive archive to generate class files for
// * @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
// * The resultant classes of the compile operation should be injected into the classloader
// * for which the given archive has a declared dependency on
// * @param targetDir a directory in which to store compiled classes, if any.
// * @return The set of classes that were compiled
// * @throws ScriptCompilationException if there was a compilation issue in the archive.
// * @throws IOException if there was a problem reading/writing the archive
// */
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException;
// }
//
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/NoOpCompiler.java
// public class NoOpCompiler implements ScriptArchiveCompiler {
//
// @Override
// public boolean shouldCompile(ScriptArchive archive) {
// return true;
// }
//
// @Override
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) {
// return Collections.<Class<?>>emptySet();
// }
// }
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/TestCompilerPlugin.java
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import com.netflix.nicobar.core.compile.ScriptArchiveCompiler;
import com.netflix.nicobar.core.internal.compile.NoOpCompiler;
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.nicobar.core.plugin;
/**
* A {@link ScriptCompilerPlugin} for script archives with a no-op compiler included.
* Intended for use during testing.
*
* @author Vasanth Asokan
*/
public class TestCompilerPlugin implements ScriptCompilerPlugin {
public static final String PLUGIN_ID = "nolang";
@Override | public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) { |
Netflix/Nicobar | nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/TestCompilerPlugin.java | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
// public interface ScriptArchiveCompiler {
// /**
// * Whether or not this compiler should be used to compile the archive
// */
// public boolean shouldCompile(ScriptArchive archive);
//
// /**
// * Compile the archive into a ScriptModule
// * @param archive archive to generate class files for
// * @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
// * The resultant classes of the compile operation should be injected into the classloader
// * for which the given archive has a declared dependency on
// * @param targetDir a directory in which to store compiled classes, if any.
// * @return The set of classes that were compiled
// * @throws ScriptCompilationException if there was a compilation issue in the archive.
// * @throws IOException if there was a problem reading/writing the archive
// */
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException;
// }
//
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/NoOpCompiler.java
// public class NoOpCompiler implements ScriptArchiveCompiler {
//
// @Override
// public boolean shouldCompile(ScriptArchive archive) {
// return true;
// }
//
// @Override
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) {
// return Collections.<Class<?>>emptySet();
// }
// }
| import java.util.Collections;
import java.util.Map;
import java.util.Set;
import com.netflix.nicobar.core.compile.ScriptArchiveCompiler;
import com.netflix.nicobar.core.internal.compile.NoOpCompiler; | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.nicobar.core.plugin;
/**
* A {@link ScriptCompilerPlugin} for script archives with a no-op compiler included.
* Intended for use during testing.
*
* @author Vasanth Asokan
*/
public class TestCompilerPlugin implements ScriptCompilerPlugin {
public static final String PLUGIN_ID = "nolang";
@Override
public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) { | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
// public interface ScriptArchiveCompiler {
// /**
// * Whether or not this compiler should be used to compile the archive
// */
// public boolean shouldCompile(ScriptArchive archive);
//
// /**
// * Compile the archive into a ScriptModule
// * @param archive archive to generate class files for
// * @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
// * The resultant classes of the compile operation should be injected into the classloader
// * for which the given archive has a declared dependency on
// * @param targetDir a directory in which to store compiled classes, if any.
// * @return The set of classes that were compiled
// * @throws ScriptCompilationException if there was a compilation issue in the archive.
// * @throws IOException if there was a problem reading/writing the archive
// */
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException;
// }
//
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/NoOpCompiler.java
// public class NoOpCompiler implements ScriptArchiveCompiler {
//
// @Override
// public boolean shouldCompile(ScriptArchive archive) {
// return true;
// }
//
// @Override
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) {
// return Collections.<Class<?>>emptySet();
// }
// }
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/plugin/TestCompilerPlugin.java
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import com.netflix.nicobar.core.compile.ScriptArchiveCompiler;
import com.netflix.nicobar.core.internal.compile.NoOpCompiler;
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.nicobar.core.plugin;
/**
* A {@link ScriptCompilerPlugin} for script archives with a no-op compiler included.
* Intended for use during testing.
*
* @author Vasanth Asokan
*/
public class TestCompilerPlugin implements ScriptCompilerPlugin {
public static final String PLUGIN_ID = "nolang";
@Override
public Set<? extends ScriptArchiveCompiler> getCompilers(Map<String, Object> compilerParams) { | return Collections.singleton(new NoOpCompiler()); |
Netflix/Nicobar | nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/NoOpCompiler.java | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
// public interface ScriptArchiveCompiler {
// /**
// * Whether or not this compiler should be used to compile the archive
// */
// public boolean shouldCompile(ScriptArchive archive);
//
// /**
// * Compile the archive into a ScriptModule
// * @param archive archive to generate class files for
// * @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
// * The resultant classes of the compile operation should be injected into the classloader
// * for which the given archive has a declared dependency on
// * @param targetDir a directory in which to store compiled classes, if any.
// * @return The set of classes that were compiled
// * @throws ScriptCompilationException if there was a compilation issue in the archive.
// * @throws IOException if there was a problem reading/writing the archive
// */
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException;
// }
//
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleClassLoader.java
// public class JBossModuleClassLoader extends ModuleClassLoader {
// private final ScriptArchive scriptArchive;
// private final Map<String, Class<?>> localClassCache;
//
// static {
// try {
// ClassLoader.registerAsParallelCapable();
// } catch (Throwable ignored) {
// }
// }
//
// public JBossModuleClassLoader(Configuration moduleClassLoaderContext, ScriptArchive scriptArchive) {
// super(moduleClassLoaderContext);
// this.scriptArchive = scriptArchive;
// this.localClassCache = new ConcurrentHashMap<String, Class<?>>(scriptArchive.getArchiveEntryNames().size());
// }
//
// /**
// * Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}.
// * This method is necessary to inject our custom {@link ModuleClassLoader} into
// * the {@link ModuleSpec}
// */
// protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) {
// return new ModuleClassLoaderFactory() {
// public ModuleClassLoader create(final Configuration configuration) {
// return AccessController.doPrivileged(
// new PrivilegedAction<JBossModuleClassLoader>() {
// public JBossModuleClassLoader run() {
// return new JBossModuleClassLoader(configuration, scriptArchive);
// }
// });
// }
// };
// }
//
// /**
// * Manually add the compiled classes to this classloader.
// * This method will not redefine the class, so that the class's
// * classloader will continue to be compiler's classloader.
// */
// public void addClasses(Set<Class<?>> classes) {
// for (Class<?> classToAdd: classes) {
// localClassCache.put(classToAdd.getName(), classToAdd);
// }
// }
//
// /**
// * Manually add the compiled classes to this classloader. This method will
// * define and resolve the class, binding this classloader to the class.
// * @return the loaded class
// */
// public Class<?> addClassBytes(String name, byte[] classBytes) {
// Class<?> newClass = defineClass(name, classBytes, 0, classBytes.length);
// resolveClass(newClass);
// localClassCache.put(newClass.getName(), newClass);
// return newClass;
// }
//
// @Override
// public Class<?> loadClassLocal(String className, boolean resolve) throws ClassNotFoundException {
// Class<?> local = localClassCache.get(className);
// if (local != null) {
// return local;
// }
// local = super.loadClassLocal(className, resolve);
// if (local != null)
// localClassCache.put(className, local);
// return local;
// }
//
// public ScriptArchive getScriptArchive() {
// return scriptArchive;
// }
//
// public Set<Class<?>> getLoadedClasses() {
// return Collections.unmodifiableSet(new HashSet<Class<?>>(localClassCache.values()));
// }
// }
| import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import com.netflix.nicobar.core.archive.ScriptArchive;
import com.netflix.nicobar.core.compile.ScriptArchiveCompiler;
import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; | /*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.nicobar.core.internal.compile;
/**
* A {@link ScriptArchiveCompiler} that does nothing. Intended for use during testing.
*
* @author Vasanth Asokan
*/
public class NoOpCompiler implements ScriptArchiveCompiler {
@Override
public boolean shouldCompile(ScriptArchive archive) {
return true;
}
@Override | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
// public interface ScriptArchiveCompiler {
// /**
// * Whether or not this compiler should be used to compile the archive
// */
// public boolean shouldCompile(ScriptArchive archive);
//
// /**
// * Compile the archive into a ScriptModule
// * @param archive archive to generate class files for
// * @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
// * The resultant classes of the compile operation should be injected into the classloader
// * for which the given archive has a declared dependency on
// * @param targetDir a directory in which to store compiled classes, if any.
// * @return The set of classes that were compiled
// * @throws ScriptCompilationException if there was a compilation issue in the archive.
// * @throws IOException if there was a problem reading/writing the archive
// */
// public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException;
// }
//
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleClassLoader.java
// public class JBossModuleClassLoader extends ModuleClassLoader {
// private final ScriptArchive scriptArchive;
// private final Map<String, Class<?>> localClassCache;
//
// static {
// try {
// ClassLoader.registerAsParallelCapable();
// } catch (Throwable ignored) {
// }
// }
//
// public JBossModuleClassLoader(Configuration moduleClassLoaderContext, ScriptArchive scriptArchive) {
// super(moduleClassLoaderContext);
// this.scriptArchive = scriptArchive;
// this.localClassCache = new ConcurrentHashMap<String, Class<?>>(scriptArchive.getArchiveEntryNames().size());
// }
//
// /**
// * Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}.
// * This method is necessary to inject our custom {@link ModuleClassLoader} into
// * the {@link ModuleSpec}
// */
// protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) {
// return new ModuleClassLoaderFactory() {
// public ModuleClassLoader create(final Configuration configuration) {
// return AccessController.doPrivileged(
// new PrivilegedAction<JBossModuleClassLoader>() {
// public JBossModuleClassLoader run() {
// return new JBossModuleClassLoader(configuration, scriptArchive);
// }
// });
// }
// };
// }
//
// /**
// * Manually add the compiled classes to this classloader.
// * This method will not redefine the class, so that the class's
// * classloader will continue to be compiler's classloader.
// */
// public void addClasses(Set<Class<?>> classes) {
// for (Class<?> classToAdd: classes) {
// localClassCache.put(classToAdd.getName(), classToAdd);
// }
// }
//
// /**
// * Manually add the compiled classes to this classloader. This method will
// * define and resolve the class, binding this classloader to the class.
// * @return the loaded class
// */
// public Class<?> addClassBytes(String name, byte[] classBytes) {
// Class<?> newClass = defineClass(name, classBytes, 0, classBytes.length);
// resolveClass(newClass);
// localClassCache.put(newClass.getName(), newClass);
// return newClass;
// }
//
// @Override
// public Class<?> loadClassLocal(String className, boolean resolve) throws ClassNotFoundException {
// Class<?> local = localClassCache.get(className);
// if (local != null) {
// return local;
// }
// local = super.loadClassLocal(className, resolve);
// if (local != null)
// localClassCache.put(className, local);
// return local;
// }
//
// public ScriptArchive getScriptArchive() {
// return scriptArchive;
// }
//
// public Set<Class<?>> getLoadedClasses() {
// return Collections.unmodifiableSet(new HashSet<Class<?>>(localClassCache.values()));
// }
// }
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/internal/compile/NoOpCompiler.java
import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import com.netflix.nicobar.core.archive.ScriptArchive;
import com.netflix.nicobar.core.compile.ScriptArchiveCompiler;
import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader;
/*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.nicobar.core.internal.compile;
/**
* A {@link ScriptArchiveCompiler} that does nothing. Intended for use during testing.
*
* @author Vasanth Asokan
*/
public class NoOpCompiler implements ScriptArchiveCompiler {
@Override
public boolean shouldCompile(ScriptArchive archive) {
return true;
}
@Override | public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) { |
Netflix/Nicobar | nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleClassLoader.java
// public class JBossModuleClassLoader extends ModuleClassLoader {
// private final ScriptArchive scriptArchive;
// private final Map<String, Class<?>> localClassCache;
//
// static {
// try {
// ClassLoader.registerAsParallelCapable();
// } catch (Throwable ignored) {
// }
// }
//
// public JBossModuleClassLoader(Configuration moduleClassLoaderContext, ScriptArchive scriptArchive) {
// super(moduleClassLoaderContext);
// this.scriptArchive = scriptArchive;
// this.localClassCache = new ConcurrentHashMap<String, Class<?>>(scriptArchive.getArchiveEntryNames().size());
// }
//
// /**
// * Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}.
// * This method is necessary to inject our custom {@link ModuleClassLoader} into
// * the {@link ModuleSpec}
// */
// protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) {
// return new ModuleClassLoaderFactory() {
// public ModuleClassLoader create(final Configuration configuration) {
// return AccessController.doPrivileged(
// new PrivilegedAction<JBossModuleClassLoader>() {
// public JBossModuleClassLoader run() {
// return new JBossModuleClassLoader(configuration, scriptArchive);
// }
// });
// }
// };
// }
//
// /**
// * Manually add the compiled classes to this classloader.
// * This method will not redefine the class, so that the class's
// * classloader will continue to be compiler's classloader.
// */
// public void addClasses(Set<Class<?>> classes) {
// for (Class<?> classToAdd: classes) {
// localClassCache.put(classToAdd.getName(), classToAdd);
// }
// }
//
// /**
// * Manually add the compiled classes to this classloader. This method will
// * define and resolve the class, binding this classloader to the class.
// * @return the loaded class
// */
// public Class<?> addClassBytes(String name, byte[] classBytes) {
// Class<?> newClass = defineClass(name, classBytes, 0, classBytes.length);
// resolveClass(newClass);
// localClassCache.put(newClass.getName(), newClass);
// return newClass;
// }
//
// @Override
// public Class<?> loadClassLocal(String className, boolean resolve) throws ClassNotFoundException {
// Class<?> local = localClassCache.get(className);
// if (local != null) {
// return local;
// }
// local = super.loadClassLocal(className, resolve);
// if (local != null)
// localClassCache.put(className, local);
// return local;
// }
//
// public ScriptArchive getScriptArchive() {
// return scriptArchive;
// }
//
// public Set<Class<?>> getLoadedClasses() {
// return Collections.unmodifiableSet(new HashSet<Class<?>>(localClassCache.values()));
// }
// }
| import java.io.IOException;
import java.nio.file.Path;
import java.util.Set;
import com.netflix.nicobar.core.archive.ScriptArchive;
import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader; | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nicobar.core.compile;
/**
* Converts a Script Archive into a Set of classes
*
* @author James Kojo
*/
public interface ScriptArchiveCompiler {
/**
* Whether or not this compiler should be used to compile the archive
*/
public boolean shouldCompile(ScriptArchive archive);
/**
* Compile the archive into a ScriptModule
* @param archive archive to generate class files for
* @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
* The resultant classes of the compile operation should be injected into the classloader
* for which the given archive has a declared dependency on
* @param targetDir a directory in which to store compiled classes, if any.
* @return The set of classes that were compiled
* @throws ScriptCompilationException if there was a compilation issue in the archive.
* @throws IOException if there was a problem reading/writing the archive
*/ | // Path: nicobar-core/src/main/java/com/netflix/nicobar/core/module/jboss/JBossModuleClassLoader.java
// public class JBossModuleClassLoader extends ModuleClassLoader {
// private final ScriptArchive scriptArchive;
// private final Map<String, Class<?>> localClassCache;
//
// static {
// try {
// ClassLoader.registerAsParallelCapable();
// } catch (Throwable ignored) {
// }
// }
//
// public JBossModuleClassLoader(Configuration moduleClassLoaderContext, ScriptArchive scriptArchive) {
// super(moduleClassLoaderContext);
// this.scriptArchive = scriptArchive;
// this.localClassCache = new ConcurrentHashMap<String, Class<?>>(scriptArchive.getArchiveEntryNames().size());
// }
//
// /**
// * Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}.
// * This method is necessary to inject our custom {@link ModuleClassLoader} into
// * the {@link ModuleSpec}
// */
// protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) {
// return new ModuleClassLoaderFactory() {
// public ModuleClassLoader create(final Configuration configuration) {
// return AccessController.doPrivileged(
// new PrivilegedAction<JBossModuleClassLoader>() {
// public JBossModuleClassLoader run() {
// return new JBossModuleClassLoader(configuration, scriptArchive);
// }
// });
// }
// };
// }
//
// /**
// * Manually add the compiled classes to this classloader.
// * This method will not redefine the class, so that the class's
// * classloader will continue to be compiler's classloader.
// */
// public void addClasses(Set<Class<?>> classes) {
// for (Class<?> classToAdd: classes) {
// localClassCache.put(classToAdd.getName(), classToAdd);
// }
// }
//
// /**
// * Manually add the compiled classes to this classloader. This method will
// * define and resolve the class, binding this classloader to the class.
// * @return the loaded class
// */
// public Class<?> addClassBytes(String name, byte[] classBytes) {
// Class<?> newClass = defineClass(name, classBytes, 0, classBytes.length);
// resolveClass(newClass);
// localClassCache.put(newClass.getName(), newClass);
// return newClass;
// }
//
// @Override
// public Class<?> loadClassLocal(String className, boolean resolve) throws ClassNotFoundException {
// Class<?> local = localClassCache.get(className);
// if (local != null) {
// return local;
// }
// local = super.loadClassLocal(className, resolve);
// if (local != null)
// localClassCache.put(className, local);
// return local;
// }
//
// public ScriptArchive getScriptArchive() {
// return scriptArchive;
// }
//
// public Set<Class<?>> getLoadedClasses() {
// return Collections.unmodifiableSet(new HashSet<Class<?>>(localClassCache.values()));
// }
// }
// Path: nicobar-core/src/main/java/com/netflix/nicobar/core/compile/ScriptArchiveCompiler.java
import java.io.IOException;
import java.nio.file.Path;
import java.util.Set;
import com.netflix.nicobar.core.archive.ScriptArchive;
import com.netflix.nicobar.core.module.jboss.JBossModuleClassLoader;
/*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.nicobar.core.compile;
/**
* Converts a Script Archive into a Set of classes
*
* @author James Kojo
*/
public interface ScriptArchiveCompiler {
/**
* Whether or not this compiler should be used to compile the archive
*/
public boolean shouldCompile(ScriptArchive archive);
/**
* Compile the archive into a ScriptModule
* @param archive archive to generate class files for
* @param moduleClassLoader class loader which can be used to find all classes and resources for modules.
* The resultant classes of the compile operation should be injected into the classloader
* for which the given archive has a declared dependency on
* @param targetDir a directory in which to store compiled classes, if any.
* @return The set of classes that were compiled
* @throws ScriptCompilationException if there was a compilation issue in the archive.
* @throws IOException if there was a problem reading/writing the archive
*/ | public Set<Class<?>> compile(ScriptArchive archive, JBossModuleClassLoader moduleClassLoader, Path targetDir) throws ScriptCompilationException, IOException; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.