index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteClientTransaction.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import java.io.IOException;
import java.net.InetAddress;
import java.util.TimerTask;
import net.sourceforge.peers.Timer;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName;
import net.sourceforge.peers.sip.transport.MessageSender;
import net.sourceforge.peers.sip.transport.SipClientTransportUser;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
import net.sourceforge.peers.sip.transport.TransportManager;
public class NonInviteClientTransaction extends NonInviteTransaction
implements ClientTransaction, SipClientTransportUser {
public final NonInviteClientTransactionState INIT;
public final NonInviteClientTransactionState TRYING;
public final NonInviteClientTransactionState PROCEEDING;
public final NonInviteClientTransactionState COMPLETED;
public final NonInviteClientTransactionState TERMINATED;
protected ClientTransactionUser transactionUser;
protected String transport;
protected int nbRetrans;
private NonInviteClientTransactionState state;
//private SipClientTransport sipClientTransport;
private MessageSender messageSender;
private int remotePort;
private InetAddress remoteInetAddress;
NonInviteClientTransaction(String branchId, InetAddress inetAddress,
int port, String transport, SipRequest sipRequest,
ClientTransactionUser transactionUser, Timer timer,
TransportManager transportManager,
TransactionManager transactionManager, Logger logger) {
super(branchId, sipRequest.getMethod(), timer, transportManager,
transactionManager, logger);
this.transport = transport;
SipHeaderFieldValue via = new SipHeaderFieldValue("");
via.addParam(new SipHeaderParamName(RFC3261.PARAM_BRANCH), branchId);
sipRequest.getSipHeaders().add(new SipHeaderFieldName(RFC3261.HDR_VIA), via, 0);
nbRetrans = 0;
INIT = new NonInviteClientTransactionStateInit(getId(), this, logger);
state = INIT;
TRYING = new NonInviteClientTransactionStateTrying(getId(), this,
logger);
PROCEEDING = new NonInviteClientTransactionStateProceeding(getId(),
this, logger);
COMPLETED = new NonInviteClientTransactionStateCompleted(getId(),
this, logger);
TERMINATED = new NonInviteClientTransactionStateTerminated(getId(),
this, logger);
request = sipRequest;
this.transactionUser = transactionUser;
remotePort = port;
remoteInetAddress = inetAddress;
try {
messageSender = transportManager.createClientTransport(
request, remoteInetAddress, remotePort, transport);
} catch (IOException e) {
logger.error("input/output error", e);
transportError();
}
//TODO send request
}
public void setState(NonInviteClientTransactionState state) {
this.state.log(state);
this.state = state;
}
public void start() {
state.start();
//17.1.2.2
// try {
// sipClientTransport = SipTransportFactory.getInstance()
// .createClientTransport(this, request, remoteInetAddress,
// remotePort, transport);
// sipClientTransport.send(request);
// } catch (IOException e) {
// //e.printStackTrace();
// transportError();
// }
try {
messageSender.sendMessage(request);
} catch (IOException e) {
logger.error("input/output error", e);
transportError();
}
if (RFC3261.TRANSPORT_UDP.equals(transport)) {
//start timer E with value T1 for retransmission
timer.schedule(new TimerE(), RFC3261.TIMER_T1);
}
timer.schedule(new TimerF(), 64 * RFC3261.TIMER_T1);
}
void sendRetrans(long delay) {
//sipClientTransport.send(request);
try {
messageSender.sendMessage(request);
} catch (IOException e) {
logger.error("input/output error", e);
transportError();
}
timer.schedule(new TimerE(), delay);
}
public void transportError() {
state.transportError();
}
public synchronized void receivedResponse(SipResponse sipResponse) {
responses.add(sipResponse);
// 17.1.1
int statusCode = sipResponse.getStatusCode();
if (statusCode < RFC3261.CODE_MIN_PROV) {
logger.error("invalid response code");
} else if (statusCode < RFC3261.CODE_MIN_SUCCESS) {
state.received1xx();
} else if (statusCode <= RFC3261.CODE_MAX) {
state.received200To699();
} else {
logger.error("invalid response code");
}
}
public void requestTransportError(SipRequest sipRequest, Exception e) {
// TODO Auto-generated method stub
}
public void responseTransportError(Exception e) {
// TODO Auto-generated method stub
}
class TimerE extends TimerTask {
@Override
public void run() {
state.timerEFires();
}
}
class TimerF extends TimerTask {
@Override
public void run() {
state.timerFFires();
}
}
class TimerK extends TimerTask {
@Override
public void run() {
state.timerKFires();
}
}
public String getContact() {
if (messageSender != null) {
return messageSender.getContact();
}
return null;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteClientTransactionState.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.AbstractState;
public abstract class NonInviteClientTransactionState extends AbstractState {
protected NonInviteClientTransaction nonInviteClientTransaction;
public NonInviteClientTransactionState(String id,
NonInviteClientTransaction nonInviteClientTransaction,
Logger logger) {
super(id, logger);
this.nonInviteClientTransaction = nonInviteClientTransaction;
}
public void start() {}
public void timerEFires() {}
public void timerFFires() {}
public void transportError() {}
public void received1xx() {}
public void received200To699() {}
public void timerKFires() {}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteClientTransactionStateCompleted.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
public class NonInviteClientTransactionStateCompleted extends
NonInviteClientTransactionState {
public NonInviteClientTransactionStateCompleted(String id,
NonInviteClientTransaction nonInviteClientTransaction,
Logger logger) {
super(id, nonInviteClientTransaction, logger);
int delay = 0;
if (RFC3261.TRANSPORT_UDP.equals(
nonInviteClientTransaction.transport)) {
delay = RFC3261.TIMER_T4;
}
nonInviteClientTransaction.timer.schedule(
nonInviteClientTransaction.new TimerK(), delay);
}
@Override
public void timerKFires() {
NonInviteClientTransactionState nextState =
nonInviteClientTransaction.TERMINATED;
nonInviteClientTransaction.setState(nextState);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteClientTransactionStateInit.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
public class NonInviteClientTransactionStateInit extends
NonInviteClientTransactionState {
public NonInviteClientTransactionStateInit(String id,
NonInviteClientTransaction nonInviteClientTransaction,
Logger logger) {
super(id, nonInviteClientTransaction, logger);
}
@Override
public void start() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.TRYING;
nonInviteClientTransaction.setState(nextState);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteClientTransactionStateProceeding.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.transport.SipResponse;
public class NonInviteClientTransactionStateProceeding extends
NonInviteClientTransactionState {
public NonInviteClientTransactionStateProceeding(String id,
NonInviteClientTransaction nonInviteClientTransaction,
Logger logger) {
super(id, nonInviteClientTransaction, logger);
}
@Override
public void timerEFires() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.PROCEEDING;
nonInviteClientTransaction.setState(nextState);
++nonInviteClientTransaction.nbRetrans;
nonInviteClientTransaction.sendRetrans(RFC3261.TIMER_T2);
}
@Override
public void timerFFires() {
timerFFiresOrTransportError();
}
@Override
public void transportError() {
timerFFiresOrTransportError();
}
private void timerFFiresOrTransportError() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.TERMINATED;
nonInviteClientTransaction.setState(nextState);
nonInviteClientTransaction.transactionUser.transactionTimeout(
nonInviteClientTransaction);
}
@Override
public void received1xx() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.PROCEEDING;
nonInviteClientTransaction.setState(nextState);
}
@Override
public void received200To699() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.COMPLETED;
nonInviteClientTransaction.setState(nextState);
SipResponse response = nonInviteClientTransaction.getLastResponse();
int code = response.getStatusCode();
if (code < RFC3261.CODE_MIN_REDIR) {
nonInviteClientTransaction.transactionUser.successResponseReceived(
response, nonInviteClientTransaction);
} else {
nonInviteClientTransaction.transactionUser.errResponseReceived(
response);
}
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteClientTransactionStateTerminated.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
public class NonInviteClientTransactionStateTerminated extends
NonInviteClientTransactionState {
public NonInviteClientTransactionStateTerminated(String id,
NonInviteClientTransaction nonInviteClientTransaction,
Logger logger) {
super(id, nonInviteClientTransaction, logger);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteClientTransactionStateTrying.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.transport.SipResponse;
public class NonInviteClientTransactionStateTrying extends
NonInviteClientTransactionState {
public NonInviteClientTransactionStateTrying(String id,
NonInviteClientTransaction nonInviteClientTransaction,
Logger logger) {
super(id, nonInviteClientTransaction, logger);
}
@Override
public void timerEFires() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.TRYING;
nonInviteClientTransaction.setState(nextState);
long delay = (long)Math.pow(2,
++nonInviteClientTransaction.nbRetrans) * RFC3261.TIMER_T1;
nonInviteClientTransaction.sendRetrans(Math.min(delay, RFC3261.TIMER_T2));
}
@Override
public void timerFFires() {
timerFFiresOrTransportError();
}
@Override
public void transportError() {
timerFFiresOrTransportError();
}
private void timerFFiresOrTransportError() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.TERMINATED;
nonInviteClientTransaction.setState(nextState);
nonInviteClientTransaction.transactionUser.transactionTimeout(
nonInviteClientTransaction);
}
@Override
public void received1xx() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.PROCEEDING;
nonInviteClientTransaction.setState(nextState);
nonInviteClientTransaction.transactionUser.provResponseReceived(
nonInviteClientTransaction.getLastResponse(), nonInviteClientTransaction);
}
@Override
public void received200To699() {
NonInviteClientTransactionState nextState = nonInviteClientTransaction.COMPLETED;
nonInviteClientTransaction.setState(nextState);
SipResponse response = nonInviteClientTransaction.getLastResponse();
int code = response.getStatusCode();
if (code < RFC3261.CODE_MIN_REDIR) {
nonInviteClientTransaction.transactionUser.successResponseReceived(
response, nonInviteClientTransaction);
} else {
nonInviteClientTransaction.transactionUser.errResponseReceived(
response);
}
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteServerTransaction.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import java.io.IOException;
import java.util.TimerTask;
import net.sourceforge.peers.Timer;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
import net.sourceforge.peers.sip.transport.TransportManager;
public class NonInviteServerTransaction extends NonInviteTransaction
implements ServerTransaction/*, SipServerTransportUser*/ {
public final NonInviteServerTransactionState TRYING;
public final NonInviteServerTransactionState PROCEEDING;
public final NonInviteServerTransactionState COMPLETED;
public final NonInviteServerTransactionState TERMINATED;
protected ServerTransactionUser serverTransactionUser;
protected Timer timer;
protected String transport;
private NonInviteServerTransactionState state;
//private int port;
NonInviteServerTransaction(String branchId, int port, String transport,
String method, ServerTransactionUser serverTransactionUser,
SipRequest sipRequest, Timer timer, TransportManager transportManager,
TransactionManager transactionManager, Logger logger) {
super(branchId, method, timer, transportManager, transactionManager,
logger);
TRYING = new NonInviteServerTransactionStateTrying(getId(), this,
logger);
state = TRYING;
PROCEEDING = new NonInviteServerTransactionStateProceeding(getId(),
this, logger);
COMPLETED = new NonInviteServerTransactionStateCompleted(getId(), this,
logger);
TERMINATED = new NonInviteServerTransactionStateTerminated(getId(),
this, logger);
//this.port = port;
this.transport = transport;
this.serverTransactionUser = serverTransactionUser;
request = sipRequest;
// sipServerTransport = SipTransportFactory.getInstance()
// .createServerTransport(this, port, transport);
try {
transportManager.createServerTransport(transport, port);
} catch (IOException e) {
logger.error("input/output error", e);
}
//TODO pass request to TU
}
public void setState(NonInviteServerTransactionState state) {
this.state.log(state);
this.state = state;
}
public void receivedRequest(SipRequest sipRequest) {
state.receivedRequest();
}
public void sendReponse(SipResponse sipResponse) {
responses.add(sipResponse);
int statusCode = sipResponse.getStatusCode();
if (statusCode < RFC3261.CODE_200_OK) {
state.received1xx();
} else if (statusCode <= RFC3261.CODE_MAX) {
state.received200To699();
}
}
void sendLastResponse() {
//sipServerTransport.sendResponse(responses.get(responses.size() - 1));
int nbOfResponses = responses.size();
if (nbOfResponses > 0) {
try {
transportManager.sendResponse(responses.get(nbOfResponses - 1));
} catch (IOException e) {
logger.error("input/output error", e);
}
}
}
public void start() {
// TODO Auto-generated method stub
}
// public void messageReceived(SipMessage sipMessage) {
// // TODO Auto-generated method stub
//
// }
class TimerJ extends TimerTask {
@Override
public void run() {
state.timerJFires();
}
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteServerTransactionState.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.AbstractState;
//17.2.2
public abstract class NonInviteServerTransactionState extends AbstractState {
protected NonInviteServerTransaction nonInviteServerTransaction;
public NonInviteServerTransactionState(String id,
NonInviteServerTransaction nonInviteServerTransaction,
Logger logger) {
super(id, logger);
this.nonInviteServerTransaction = nonInviteServerTransaction;
}
public void received200To699() {}
public void received1xx() {}
public void receivedRequest() {}
public void transportError() {}
public void timerJFires() {}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteServerTransactionStateCompleted.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
public class NonInviteServerTransactionStateCompleted extends
NonInviteServerTransactionState {
public NonInviteServerTransactionStateCompleted(String id,
NonInviteServerTransaction nonInviteServerTransaction,
Logger logger) {
super(id, nonInviteServerTransaction, logger);
}
@Override
public void timerJFires() {
NonInviteServerTransactionState nextState = nonInviteServerTransaction.TERMINATED;
nonInviteServerTransaction.setState(nextState);
}
@Override
public void transportError() {
NonInviteServerTransactionState nextState = nonInviteServerTransaction.TERMINATED;
nonInviteServerTransaction.setState(nextState);
}
@Override
public void receivedRequest() {
NonInviteServerTransactionState nextState = nonInviteServerTransaction.COMPLETED;
nonInviteServerTransaction.setState(nextState);
nonInviteServerTransaction.sendLastResponse();
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteServerTransactionStateProceeding.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
public class NonInviteServerTransactionStateProceeding extends
NonInviteServerTransactionState {
public NonInviteServerTransactionStateProceeding(String id,
NonInviteServerTransaction nonInviteServerTransaction,
Logger logger) {
super(id, nonInviteServerTransaction, logger);
}
@Override
public void received1xx() {
NonInviteServerTransactionState nextState =
nonInviteServerTransaction.PROCEEDING;
nonInviteServerTransaction.setState(nextState);
nonInviteServerTransaction.sendLastResponse();
}
@Override
public void received200To699() {
NonInviteServerTransactionState nextState =
nonInviteServerTransaction.COMPLETED;
nonInviteServerTransaction.setState(nextState);
nonInviteServerTransaction.sendLastResponse();
int timeout;
if (RFC3261.TRANSPORT_UDP.equals(
nonInviteServerTransaction.transport)) {
timeout = 64 * RFC3261.TIMER_T1;
} else {
timeout = 0;
}
nonInviteServerTransaction.timer.schedule(
nonInviteServerTransaction.new TimerJ(), timeout);
}
@Override
public void transportError() {
NonInviteServerTransactionState nextState =
nonInviteServerTransaction.TERMINATED;
nonInviteServerTransaction.setState(nextState);
}
@Override
public void receivedRequest() {
NonInviteServerTransactionState nextState =
nonInviteServerTransaction.PROCEEDING;
nonInviteServerTransaction.setState(nextState);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteServerTransactionStateTerminated.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
public class NonInviteServerTransactionStateTerminated extends
NonInviteServerTransactionState {
public NonInviteServerTransactionStateTerminated(String id,
NonInviteServerTransaction nonInviteServerTransaction,
Logger logger) {
super(id, nonInviteServerTransaction, logger);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteServerTransactionStateTrying.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Logger;
public class NonInviteServerTransactionStateTrying extends
NonInviteServerTransactionState {
public NonInviteServerTransactionStateTrying(String id,
NonInviteServerTransaction nonInviteServerTransaction,
Logger logger) {
super(id, nonInviteServerTransaction, logger);
}
@Override
public void received1xx() {
NonInviteServerTransactionState nextState =
nonInviteServerTransaction.PROCEEDING;
nonInviteServerTransaction.setState(nextState);
nonInviteServerTransaction.sendLastResponse();
}
@Override
public void received200To699() {
NonInviteServerTransactionState nextState =
nonInviteServerTransaction.COMPLETED;
nonInviteServerTransaction.setState(nextState);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/NonInviteTransaction.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.Timer;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.transport.TransportManager;
public abstract class NonInviteTransaction extends Transaction {
protected NonInviteTransaction(String branchId, String method, Timer timer,
TransportManager transportManager,
TransactionManager transactionManager, Logger logger) {
super(branchId, method, timer, transportManager, transactionManager,
logger);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/ServerTransaction.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
public interface ServerTransaction {
public void start();
public void receivedRequest(SipRequest sipRequest);
public void sendReponse(SipResponse sipResponse);
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/ServerTransactionUser.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
public interface ServerTransactionUser {
public void transactionFailure();
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/SipListeningPoint.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
public class SipListeningPoint {
private int localPort;
private String localTransport;
public SipListeningPoint(int localPort, String localTransport) {
super();
this.localPort = localPort;
this.localTransport = localTransport;
}
@Override
public boolean equals(Object obj) {
if (obj.getClass() != SipListeningPoint.class) {
return false;
}
SipListeningPoint other = (SipListeningPoint)obj;
return localPort == other.localPort &&
localTransport.equals(other.localTransport);
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(':').append(localPort).append('/').append(localTransport);
return buf.toString();
}
@Override
public int hashCode() {
return toString().hashCode();
}
public int getlocalPort() {
return localPort;
}
public String getlocalTransport() {
return localTransport;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/Transaction.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007-2013 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.sourceforge.peers.Timer;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
import net.sourceforge.peers.sip.transport.TransportManager;
public abstract class Transaction {
public static final char ID_SEPARATOR = '|';
protected String branchId;
protected String method;
protected SipRequest request;
protected List<SipResponse> responses;
protected Timer timer;
protected TransportManager transportManager;
protected TransactionManager transactionManager;
protected Logger logger;
protected Transaction(String branchId, String method, Timer timer,
TransportManager transportManager,
TransactionManager transactionManager, Logger logger) {
this.branchId = branchId;
this.method = method;
this.timer = timer;
this.transportManager = transportManager;
this.transactionManager = transactionManager;
this.logger = logger;
responses = Collections.synchronizedList(new ArrayList<SipResponse>());
}
protected String getId() {
StringBuffer buf = new StringBuffer();
buf.append(branchId).append(ID_SEPARATOR);
buf.append(method);
return buf.toString();
}
public SipResponse getLastResponse() {
if (responses.isEmpty()) {
return null;
}
return responses.get(responses.size() - 1);
}
public SipRequest getRequest() {
return request;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transaction/TransactionManager.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007-2013 Yohann Martineau
*/
package net.sourceforge.peers.sip.transaction;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import net.sourceforge.peers.Timer;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.Utils;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName;
import net.sourceforge.peers.sip.transport.SipMessage;
import net.sourceforge.peers.sip.transport.SipRequest;
import net.sourceforge.peers.sip.transport.SipResponse;
import net.sourceforge.peers.sip.transport.TransportManager;
public class TransactionManager {
protected Timer timer;
// TODO remove client transactions when they reach terminated state
// TODO check that server transactions are removed in all transitions to terminated
private Hashtable<String, ClientTransaction> clientTransactions;
private Hashtable<String, ServerTransaction> serverTransactions;
private TransportManager transportManager;
private Logger logger;
public TransactionManager(Logger logger) {
this.logger = logger;
clientTransactions = new Hashtable<String, ClientTransaction>();
serverTransactions = new Hashtable<String, ServerTransaction>();
timer = new Timer(TransactionManager.class.getSimpleName()
+ " " + Timer.class.getSimpleName());
}
public void closeTimers() {
timer.cancel();
}
public ClientTransaction createClientTransaction(SipRequest sipRequest,
InetAddress inetAddress, int port, String transport,
String pBranchId, ClientTransactionUser clientTransactionUser) {
String branchId;
if (pBranchId == null || "".equals(pBranchId.trim())
|| !pBranchId.startsWith(RFC3261.BRANCHID_MAGIC_COOKIE)) {
branchId = Utils.generateBranchId();
} else {
branchId = pBranchId;
}
String method = sipRequest.getMethod();
ClientTransaction clientTransaction;
if (RFC3261.METHOD_INVITE.equals(method)) {
clientTransaction = new InviteClientTransaction(branchId,
inetAddress, port, transport, sipRequest, clientTransactionUser,
timer, transportManager, this, logger);
} else {
clientTransaction = new NonInviteClientTransaction(branchId,
inetAddress, port, transport, sipRequest, clientTransactionUser,
timer, transportManager, this, logger);
}
clientTransactions.put(getTransactionId(branchId, method),
clientTransaction);
return clientTransaction;
}
public ServerTransaction createServerTransaction(SipResponse sipResponse,
int port, String transport,
ServerTransactionUser serverTransactionUser,
SipRequest sipRequest) {
SipHeaderFieldValue via = Utils.getTopVia(sipResponse);
String branchId = via.getParam(new SipHeaderParamName(
RFC3261.PARAM_BRANCH));
String cseq = sipResponse.getSipHeaders().get(
new SipHeaderFieldName(RFC3261.HDR_CSEQ)).toString();
String method = cseq.substring(cseq.lastIndexOf(' ') + 1);
ServerTransaction serverTransaction;
// TODO create server transport user and pass it to server transaction
if (RFC3261.METHOD_INVITE.equals(method)) {
serverTransaction = new InviteServerTransaction(branchId, port,
transport, sipResponse, serverTransactionUser, sipRequest,
timer, this, transportManager, logger);
// serverTransaction = new InviteServerTransaction(branchId);
} else {
serverTransaction = new NonInviteServerTransaction(branchId, port,
transport, method, serverTransactionUser, sipRequest, timer,
transportManager, this, logger);
}
serverTransactions.put(getTransactionId(branchId, method),
serverTransaction);
return serverTransaction;
}
public ClientTransaction getClientTransaction(SipMessage sipMessage) {
SipHeaderFieldValue via = Utils.getTopVia(sipMessage);
String branchId = via.getParam(new SipHeaderParamName(
RFC3261.PARAM_BRANCH));
String cseq = sipMessage.getSipHeaders().get(
new SipHeaderFieldName(RFC3261.HDR_CSEQ)).toString();
String method = cseq.substring(cseq.lastIndexOf(' ') + 1);
return clientTransactions.get(getTransactionId(branchId, method));
}
public List<ClientTransaction> getClientTransactionsFromCallId(String callId,
String method) {
ArrayList<ClientTransaction> clientTransactionsFromCallId =
new ArrayList<ClientTransaction>();
for (ClientTransaction clientTransaction: clientTransactions.values()) {
Transaction transaction = (Transaction)clientTransaction;
SipRequest sipRequest = transaction.getRequest();
String reqCallId = Utils.getMessageCallId(sipRequest);
String reqMethod = sipRequest.getMethod();
if (reqCallId.equals(callId) && method.equals(reqMethod)) {
clientTransactionsFromCallId.add(clientTransaction);
}
}
return clientTransactionsFromCallId;
}
public ServerTransaction getServerTransaction(SipMessage sipMessage) {
SipHeaderFieldValue via = Utils.getTopVia(sipMessage);
String branchId = via.getParam(new SipHeaderParamName(
RFC3261.PARAM_BRANCH));
String method;
if (sipMessage instanceof SipRequest) {
method = ((SipRequest)sipMessage).getMethod();
} else {
String cseq = sipMessage.getSipHeaders().get(
new SipHeaderFieldName(RFC3261.HDR_CSEQ)).toString();
method = cseq.substring(cseq.lastIndexOf(' ') + 1);
}
if (RFC3261.METHOD_ACK.equals(method)) {
method = RFC3261.METHOD_INVITE;
// InviteServerTransaction inviteServerTransaction =
// (InviteServerTransaction)
// serverTransactions.get(getTransactionId(branchId, method));
// if (inviteServerTransaction == null) {
// Logger.debug("received ACK for unknown transaction" +
// " branchId = " + branchId + ", method = " + method);
// } else {
// SipResponse sipResponse =
// inviteServerTransaction.getLastResponse();
// if (sipResponse == null) {
// Logger.debug("received ACK but no response sent " +
// "branchId = " + branchId + ", method = " + method);
// } else {
// int statusCode = sipResponse.getStatusCode();
// if (statusCode >= RFC3261.CODE_MIN_SUCCESS &&
// statusCode < RFC3261.CODE_MIN_REDIR) {
// // success response => ACK is not in INVITE server
// // transaction
// return null;
// } else {
// // error => ACK belongs to INVITE server transaction
// return inviteServerTransaction;
// }
// }
// }
// TODO if positive response, ACK does not belong to transaction
// retrieve transaction and take responses from transaction
// and check if a positive response has been received
// if it is the case, a new standalone transaction must be created
// for the ACK
}
return serverTransactions.get(getTransactionId(branchId, method));
}
public ServerTransaction getServerTransaction(String branchId, String method) {
return serverTransactions.get(getTransactionId(branchId, method));
}
void removeServerTransaction(String branchId, String method) {
serverTransactions.remove(getTransactionId(branchId, method));
}
void removeClientTransaction(String branchId, String method) {
clientTransactions.remove(getTransactionId(branchId, method));
}
private String getTransactionId(String branchId, String method) {
StringBuffer buf = new StringBuffer();
buf.append(branchId);
buf.append(Transaction.ID_SEPARATOR);
buf.append(method);
return buf.toString();
}
public void setTransportManager(TransportManager transportManager) {
this.transportManager = transportManager;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transactionuser/Dialog.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transactionuser;
import java.util.ArrayList;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.Utils;
import net.sourceforge.peers.sip.syntaxencoding.NameAddress;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldMultiValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaders;
import net.sourceforge.peers.sip.syntaxencoding.SipURI;
import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException;
import net.sourceforge.peers.sip.transport.SipRequest;
public class Dialog {
public static final char ID_SEPARATOR = '|';
public static final int EMPTY_CSEQ = -1;
public final DialogState INIT;
public final DialogState EARLY;
public final DialogState CONFIRMED;
public final DialogState TERMINATED;
private DialogState state;
private String callId;
private String localTag;
private String remoteTag;
private int localCSeq;
private int remoteCSeq;
private String localUri;
private String remoteUri;
private String remoteTarget;
private boolean secure;
private ArrayList<String> routeSet;
private Logger logger;
Dialog(String callId, String localTag, String remoteTag, Logger logger) {
super();
this.callId = callId;
this.localTag = localTag;
this.remoteTag = remoteTag;
this.logger = logger;
INIT = new DialogStateInit(getId(), this, logger);
state = INIT;
EARLY = new DialogStateEarly(getId(), this, logger);
CONFIRMED = new DialogStateConfirmed(getId(), this, logger);
TERMINATED = new DialogStateTerminated(getId(), this, logger);
localCSeq = EMPTY_CSEQ;
remoteCSeq = EMPTY_CSEQ;
}
public void receivedOrSent1xx() {
state.receivedOrSent101To199();
}
public void receivedOrSent2xx() {
state.receivedOrSent2xx();
}
public void receivedOrSent300To699() {
state.receivedOrSent300To699();
}
public void receivedOrSentBye() {
state.receivedOrSentBye();
}
public void setState(DialogState state) {
this.state.log(state);
this.state = state;
}
public SipRequest buildSubsequentRequest(String method) {
//12.2.1.1
SipURI sipUri;
try {
sipUri = new SipURI(remoteTarget);
} catch (SipUriSyntaxException e) {
throw new RuntimeException(e);
//TODO check remote target when message is received
}
SipRequest subsequentRequest = new SipRequest(method, sipUri);
SipHeaders headers = subsequentRequest.getSipHeaders();
//To
SipHeaderFieldValue to = new SipHeaderFieldValue(
new NameAddress(remoteUri).toString());
if (remoteTag != null) {
to.addParam(new SipHeaderParamName(RFC3261.PARAM_TAG), remoteTag);
}
headers.add(new SipHeaderFieldName(RFC3261.HDR_TO), to);
//From
SipHeaderFieldValue from = new SipHeaderFieldValue(
new NameAddress(localUri).toString());
if (localTag != null) {
from.addParam(new SipHeaderParamName(RFC3261.PARAM_TAG), localTag);
}
headers.add(new SipHeaderFieldName(RFC3261.HDR_FROM), from);
//Call-ID
SipHeaderFieldValue callIdValue = new SipHeaderFieldValue(callId);
headers.add(new SipHeaderFieldName(RFC3261.HDR_CALLID), callIdValue);
//CSeq
if (localCSeq == Dialog.EMPTY_CSEQ) {
localCSeq = ((int)(System.currentTimeMillis() / 1000) & 0xFFFFFFFE) >> 1;
} else {
localCSeq++;
}
headers.add(new SipHeaderFieldName(RFC3261.HDR_CSEQ),
new SipHeaderFieldValue(localCSeq + " " + method));
//Route
if (!routeSet.isEmpty()) {
if (routeSet.get(0).contains(RFC3261.LOOSE_ROUTING)) {
ArrayList<SipHeaderFieldValue> routes = new ArrayList<SipHeaderFieldValue>();
for (String route : routeSet) {
routes.add(new SipHeaderFieldValue(route));
}
headers.add(new SipHeaderFieldName(RFC3261.HDR_ROUTE),
new SipHeaderFieldMultiValue(routes));
} else {
logger.error("Trying to forward to a strict router, forbidden in this implementation");
}
}
Utils.addCommonHeaders(headers);
return subsequentRequest;
}
public String getId() {
StringBuffer buf = new StringBuffer();
buf.append(callId).append(ID_SEPARATOR);
buf.append(localTag).append(ID_SEPARATOR);
buf.append(remoteTag);
return buf.toString();
}
public String getCallId() {
return callId;
}
public void setCallId(String callId) {
this.callId = callId;
}
public int getLocalCSeq() {
return localCSeq;
}
public void setLocalCSeq(int localCSeq) {
this.localCSeq = localCSeq;
}
public String getLocalUri() {
return localUri;
}
public void setLocalUri(String localUri) {
this.localUri = localUri;
}
public int getRemoteCSeq() {
return remoteCSeq;
}
public void setRemoteCSeq(int remoteCSeq) {
this.remoteCSeq = remoteCSeq;
}
public String getRemoteTarget() {
return remoteTarget;
}
public void setRemoteTarget(String remoteTarget) {
this.remoteTarget = remoteTarget;
}
public String getRemoteUri() {
return remoteUri;
}
public void setRemoteUri(String remoteUri) {
this.remoteUri = remoteUri;
}
public ArrayList<String> getRouteSet() {
return routeSet;
}
public void setRouteSet(ArrayList<String> routeSet) {
this.routeSet = routeSet;
}
public boolean isSecure() {
return secure;
}
public void setSecure(boolean secure) {
this.secure = secure;
}
public String getLocalTag() {
return localTag;
}
public void setLocalTag(String localTag) {
this.localTag = localTag;
}
public String getRemoteTag() {
return remoteTag;
}
public void setRemoteTag(String remoteTag) {
this.remoteTag = remoteTag;
}
public DialogState getState() {
return state;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transactionuser/DialogManager.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transactionuser;
import java.util.Collection;
import java.util.Hashtable;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaders;
import net.sourceforge.peers.sip.transport.SipMessage;
import net.sourceforge.peers.sip.transport.SipResponse;
public class DialogManager {
private Hashtable<String, Dialog> dialogs;
private Logger logger;
public DialogManager(Logger logger) {
this.logger = logger;
dialogs = new Hashtable<String, Dialog>();
}
/**
* @param sipResponse sip response must contain a To tag, a
* From tag and a Call-ID
* @return the new Dialog created
*/
public synchronized Dialog createDialog(SipResponse sipResponse) {
SipHeaders sipHeaders = sipResponse.getSipHeaders();
String callID = sipHeaders.get(
new SipHeaderFieldName(RFC3261.HDR_CALLID)).toString();
SipHeaderFieldValue from = sipHeaders.get(
new SipHeaderFieldName(RFC3261.HDR_FROM));
SipHeaderFieldValue to = sipHeaders.get(
new SipHeaderFieldName(RFC3261.HDR_TO));
String fromTag = from.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG));
String toTag = to.getParam(new SipHeaderParamName(RFC3261.PARAM_TAG));
Dialog dialog;
if (sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_VIA)) == null) {
//createDialog is called from UAS side, in layer Transaction User
dialog = new Dialog(callID, toTag, fromTag, logger);
} else {
//createDialog is called from UAC side, in syntax encoding layer
dialog = new Dialog(callID, fromTag, toTag, logger);
}
dialogs.put(dialog.getId(), dialog);
return dialog;
}
public void removeDialog(String dialogId) {
dialogs.remove(dialogId);
}
public synchronized Dialog getDialog(SipMessage sipMessage) {
SipHeaders sipHeaders = sipMessage.getSipHeaders();
String callID = sipHeaders.get(
new SipHeaderFieldName(RFC3261.HDR_CALLID)).toString();
SipHeaderFieldValue from = sipHeaders.get(
new SipHeaderFieldName(RFC3261.HDR_FROM));
SipHeaderFieldValue to = sipHeaders.get(
new SipHeaderFieldName(RFC3261.HDR_TO));
SipHeaderParamName tagName = new SipHeaderParamName(RFC3261.PARAM_TAG);
String fromTag = from.getParam(tagName);
String toTag = to.getParam(tagName);
Dialog dialog = dialogs.get(getDialogId(callID, fromTag, toTag));
if (dialog != null) {
return dialog;
}
return dialogs.get(getDialogId(callID, toTag, fromTag));
}
public synchronized Dialog getDialog(String callId) {
for (Dialog dialog : dialogs.values()) {
if (dialog.getCallId().equals(callId)) {
return dialog;
}
}
return null;
}
private String getDialogId(String callID, String localTag, String remoteTag) {
StringBuffer buf = new StringBuffer();
buf.append(callID);
buf.append(Dialog.ID_SEPARATOR);
buf.append(localTag);
buf.append(Dialog.ID_SEPARATOR);
buf.append(remoteTag);
return buf.toString();
}
public Collection<Dialog> getDialogCollection() {
return dialogs.values();
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transactionuser/DialogState.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transactionuser;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.AbstractState;
public abstract class DialogState extends AbstractState {
protected Dialog dialog;
public DialogState(String id, Dialog dialog, Logger logger) {
super(id, logger);
this.dialog = dialog;
}
public void receivedOrSent101To199() {}
public void receivedOrSent2xx() {}
public void receivedOrSent300To699() {}
//sent or received a BYE for RFC3261
public void receivedOrSentBye() {}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transactionuser/DialogStateConfirmed.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transactionuser;
import net.sourceforge.peers.Logger;
public class DialogStateConfirmed extends DialogState {
public DialogStateConfirmed(String id, Dialog dialog, Logger logger) {
super(id, dialog, logger);
}
@Override
public void receivedOrSent101To199() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
@Override
public void receivedOrSent2xx() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
@Override
public void receivedOrSent300To699() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
@Override
public void receivedOrSentBye() {
DialogState nextState = dialog.TERMINATED;
dialog.setState(nextState);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transactionuser/DialogStateEarly.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transactionuser;
import net.sourceforge.peers.Logger;
public class DialogStateEarly extends DialogState {
public DialogStateEarly(String id, Dialog dialog, Logger logger) {
super(id, dialog, logger);
}
@Override
public void receivedOrSent101To199() {
DialogState nextState = dialog.EARLY;
dialog.setState(nextState);
}
@Override
public void receivedOrSent2xx() {
DialogState nextState = dialog.CONFIRMED;
dialog.setState(nextState);
}
@Override
public void receivedOrSent300To699() {
DialogState nextState = dialog.TERMINATED;
dialog.setState(nextState);
}
@Override
public void receivedOrSentBye() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transactionuser/DialogStateInit.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transactionuser;
import net.sourceforge.peers.Logger;
public class DialogStateInit extends DialogState {
public DialogStateInit(String id, Dialog dialog, Logger logger) {
super(id, dialog, logger);
}
@Override
public void receivedOrSent101To199() {
DialogState nextState = dialog.EARLY;
dialog.setState(nextState);
}
@Override
public void receivedOrSent2xx() {
DialogState nextState = dialog.CONFIRMED;
dialog.setState(nextState);
}
@Override
public void receivedOrSent300To699() {
DialogState nextState = dialog.TERMINATED;
dialog.setState(nextState);
}
@Override
public void receivedOrSentBye() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transactionuser/DialogStateTerminated.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007-2013 Yohann Martineau
*/
package net.sourceforge.peers.sip.transactionuser;
import net.sourceforge.peers.Logger;
public class DialogStateTerminated extends DialogState {
public DialogStateTerminated(String id, Dialog dialog, Logger logger) {
super(id, dialog, logger);
}
@Override
public void receivedOrSent101To199() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
@Override
public void receivedOrSent2xx() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
@Override
public void receivedOrSent300To699() {
logger.error(id + " invalid transition");
throw new IllegalStateException();
}
@Override
public void receivedOrSentBye() {
//ignore bye retransmissions
// logger.error(id + " invalid transition");
// throw new IllegalStateException();
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/MessageReceiver.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.Utils;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName;
import net.sourceforge.peers.sip.syntaxencoding.SipParserException;
import net.sourceforge.peers.sip.transaction.ClientTransaction;
import net.sourceforge.peers.sip.transaction.ServerTransaction;
import net.sourceforge.peers.sip.transaction.TransactionManager;
public abstract class MessageReceiver implements Runnable {
public static final int BUFFER_SIZE = 2048;//FIXME should correspond to MTU 1024;
public static final String CHARACTER_ENCODING = "US-ASCII";
protected int port;
private boolean isListening;
//private UAS uas;
private SipServerTransportUser sipServerTransportUser;
private TransactionManager transactionManager;
private TransportManager transportManager;
private Config config;
protected Logger logger;
public MessageReceiver(int port, TransactionManager transactionManager,
TransportManager transportManager, Config config, Logger logger) {
super();
this.port = port;
this.transactionManager = transactionManager;
this.transportManager = transportManager;
this.config = config;
this.logger = logger;
isListening = true;
}
public void run() {
while (isListening) {
try {
listen();
} catch (IOException e) {
logger.error("input/output error", e);
}
}
}
protected abstract void listen() throws IOException;
protected boolean isRequest(byte[] message) {
String beginning = null;
try {
beginning = new String(message, 0,
RFC3261.DEFAULT_SIP_VERSION.length(), CHARACTER_ENCODING);
} catch (UnsupportedEncodingException e) {
logger.error("unsupported encoding", e);
}
if (RFC3261.DEFAULT_SIP_VERSION.equals(beginning)) {
return false;
}
return true;
}
protected void processMessage(byte[] message, InetAddress sourceIp,
int sourcePort, String transport) throws IOException {
ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(message);
InputStreamReader inputStreamReader = new InputStreamReader(
byteArrayInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String startLine = reader.readLine();
while ("".equals(startLine)) {
startLine = reader.readLine();
}
if (startLine == null) {
return;
}
if (!startLine.contains(RFC3261.DEFAULT_SIP_VERSION)) {
// keep-alive, send back to sender
SipTransportConnection sipTransportConnection =
new SipTransportConnection(config.getLocalInetAddress(),
port, sourceIp, sourcePort, transport);
MessageSender messageSender = transportManager.getMessageSender(
sipTransportConnection);
if (messageSender != null) {
messageSender.sendBytes(message);
}
return;
}
StringBuffer direction = new StringBuffer();
direction.append("RECEIVED from ").append(sourceIp.getHostAddress());
direction.append("/").append(sourcePort);
logger.traceNetwork(new String(message),
direction.toString());
SipMessage sipMessage = null;
try {
sipMessage = transportManager.sipParser.parse(
new ByteArrayInputStream(message));
} catch (IOException e) {
logger.error("input/output error", e);
} catch (SipParserException e) {
logger.error("SIP parser error", e);
}
if (sipMessage == null) {
return;
}
// RFC3261 18.2
if (sipMessage instanceof SipRequest) {
SipRequest sipRequest = (SipRequest)sipMessage;
SipHeaderFieldValue topVia = Utils.getTopVia(sipRequest);
String sentBy =
topVia.getParam(new SipHeaderParamName(RFC3261.PARAM_SENTBY));
if (sentBy != null) {
int colonPos = sentBy.indexOf(RFC3261.TRANSPORT_PORT_SEP);
if (colonPos < 0) {
colonPos = sentBy.length();
}
sentBy = sentBy.substring(0, colonPos);
if (!InetAddress.getByName(sentBy).equals(sourceIp)) {
topVia.addParam(new SipHeaderParamName(
RFC3261.PARAM_RECEIVED),
sourceIp.getHostAddress());
}
}
//RFC3581
//TODO check rport configuration
SipHeaderParamName rportName = new SipHeaderParamName(
RFC3261.PARAM_RPORT);
String rport = topVia.getParam(rportName);
if (rport != null && "".equals(rport)) {
topVia.removeParam(rportName);
topVia.addParam(rportName, String.valueOf(sourcePort));
}
ServerTransaction serverTransaction =
transactionManager.getServerTransaction(sipRequest);
if (serverTransaction == null) {
//uas.messageReceived(sipMessage);
sipServerTransportUser.messageReceived(sipMessage);
} else {
serverTransaction.receivedRequest(sipRequest);
}
} else {
SipResponse sipResponse = (SipResponse)sipMessage;
ClientTransaction clientTransaction =
transactionManager.getClientTransaction(sipResponse);
logger.debug("ClientTransaction = " + clientTransaction);
if (clientTransaction == null) {
//uas.messageReceived(sipMessage);
sipServerTransportUser.messageReceived(sipMessage);
} else {
clientTransaction.receivedResponse(sipResponse);
}
}
}
public synchronized void setListening(boolean isListening) {
this.isListening = isListening;
}
public synchronized boolean isListening() {
return isListening;
}
public void setSipServerTransportUser(
SipServerTransportUser sipServerTransportUser) {
this.sipServerTransportUser = sipServerTransportUser;
}
// public void setUas(UAS uas) {
// this.uas = uas;
// }
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/MessageSender.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007-2013 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import java.io.IOException;
import java.net.InetAddress;
import java.util.TimerTask;
import net.sourceforge.peers.Timer;
import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
public abstract class MessageSender {
public static final int KEEY_ALIVE_INTERVAL = 25; // seconds
protected InetAddress inetAddress;
protected int port;
protected int localPort;
private Config config;
private String transportName;
private Timer timer;
protected Logger logger;
public MessageSender(int localPort, InetAddress inetAddress,
int port, Config config,
String transportName, Logger logger) {
super();
this.localPort = localPort;
this.inetAddress = inetAddress;
this.port = port;
this.config = config;
this.transportName = transportName;
timer = new Timer(getClass().getSimpleName() + " "
+ Timer.class.getSimpleName());
this.logger = logger;
//TODO check config
timer.scheduleAtFixedRate(new KeepAlive(), 0,
1000 * KEEY_ALIVE_INTERVAL);
}
public abstract void sendMessage(SipMessage sipMessage) throws IOException;
public abstract void sendBytes(byte[] bytes) throws IOException;
public String getContact() {
StringBuffer buf = new StringBuffer();
InetAddress myAddress = config.getPublicInetAddress();
if (myAddress == null) {
myAddress = config.getLocalInetAddress();
}
buf.append(myAddress.getHostAddress());
buf.append(RFC3261.TRANSPORT_PORT_SEP);
//buf.append(config.getSipPort());
buf.append(localPort);
buf.append(RFC3261.PARAM_SEPARATOR);
buf.append(RFC3261.PARAM_TRANSPORT);
buf.append(RFC3261.PARAM_ASSIGNMENT);
buf.append(transportName);
return buf.toString();
}
public int getLocalPort() {
return localPort;
}
public void stopKeepAlives() {
timer.cancel();
}
class KeepAlive extends TimerTask {
@Override
public void run() {
byte[] bytes = (RFC3261.CRLF + RFC3261.CRLF).getBytes();
try {
sendBytes(bytes);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/SipClientTransportUser.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
public interface SipClientTransportUser {
public void requestTransportError(SipRequest sipRequest, Exception e);
public void responseTransportError(Exception e);
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/SipMessage.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaders;
public abstract class SipMessage {
protected String sipVersion;
protected SipHeaders sipHeaders;
protected byte[] body;
public SipMessage() {
sipVersion = RFC3261.DEFAULT_SIP_VERSION;
sipHeaders = new SipHeaders();
}
public String getSipVersion() {
return sipVersion;
}
public void setSipHeaders(SipHeaders sipHeaders) {
this.sipHeaders = sipHeaders;
}
public SipHeaders getSipHeaders() {
return sipHeaders;
}
public byte[] getBody() {
return body;
}
public void setBody(byte[] body) {
SipHeaderFieldName contentLengthName =
new SipHeaderFieldName(RFC3261.HDR_CONTENT_LENGTH);
SipHeaderFieldValue contentLengthValue =
sipHeaders.get(contentLengthName);
if (contentLengthValue == null) {
contentLengthValue = new SipHeaderFieldValue(
String.valueOf(body.length));
sipHeaders.add(contentLengthName, contentLengthValue);
} else {
contentLengthValue.setValue(String.valueOf(body.length));
}
this.body = body;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(sipHeaders.toString());
buf.append(RFC3261.CRLF);
if (body != null) {
buf.append(new String(body));
}
return buf.toString();
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/SipRequest.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.syntaxencoding.SipURI;
public class SipRequest extends SipMessage {
protected String method;
protected SipURI requestUri;
//protected String requestUri;
public SipRequest(String method, SipURI requestUri) {
super();
this.method = method;
this.requestUri = requestUri;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(method).append(' ').append(requestUri).append(
' ').append(RFC3261.DEFAULT_SIP_VERSION).append(RFC3261.CRLF);
buf.append(super.toString());
return buf.toString();
}
public String getMethod() {
return method;
}
public SipURI getRequestUri() {
return requestUri;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/SipResponse.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import net.sourceforge.peers.sip.RFC3261;
public class SipResponse extends SipMessage {
protected int statusCode;
protected String reasonPhrase;
public SipResponse(int statusCode, String reasonPhrase) {
this.statusCode = statusCode;
this.reasonPhrase = reasonPhrase;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(RFC3261.DEFAULT_SIP_VERSION).append(' ').append(statusCode
).append(' ').append(reasonPhrase).append(RFC3261.CRLF);
buf.append(super.toString());
return buf.toString();
}
public int getStatusCode() {
return statusCode;
}
public String getReasonPhrase() {
return reasonPhrase;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/SipServerTransportUser.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
public interface SipServerTransportUser {
public void messageReceived(SipMessage sipMessage);
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/SipTransportConnection.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007-2013 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import java.net.InetAddress;
import net.sourceforge.peers.sip.RFC3261;
public class SipTransportConnection {
public static final int EMPTY_PORT = -1;
private InetAddress localInetAddress;
private int localPort = EMPTY_PORT;
private InetAddress remoteInetAddress;
private int remotePort = EMPTY_PORT;
private String transport;// UDP, TCP or SCTP
public SipTransportConnection(InetAddress localInetAddress,
int localPort, InetAddress remoteInetAddress, int remotePort,
String transport) {
this.localInetAddress = localInetAddress;
this.localPort = localPort;
this.remoteInetAddress = remoteInetAddress;
this.remotePort = remotePort;
this.transport = transport;
}
@Override
public boolean equals(Object obj) {
if (obj.getClass() != SipTransportConnection.class) {
return false;
}
SipTransportConnection other = (SipTransportConnection)obj;
if (!transport.equalsIgnoreCase(other.transport)) {
return false;
}
if (RFC3261.TRANSPORT_UDP.equalsIgnoreCase(transport)) {
return localInetAddress.equals(other.localInetAddress) &&
localPort == other.localPort;
}
return false;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
appendInetAddress(buf, localInetAddress);
buf.append(':');
appendPort(buf, localPort);
buf.append('/');
if (!RFC3261.TRANSPORT_UDP.equalsIgnoreCase(transport)) {
appendInetAddress(buf, remoteInetAddress);
buf.append(':');
appendPort(buf, remotePort);
buf.append('/');
}
buf.append(transport.toUpperCase());
return buf.toString();
}
private void appendInetAddress(StringBuffer buf, InetAddress inetAddress) {
if (inetAddress != null) {
buf.append(inetAddress.getHostAddress());
} else {
buf.append("-");
}
}
private void appendPort(StringBuffer buf, int port) {
if (port != EMPTY_PORT) {
buf.append(port);
} else {
buf.append("-");
}
}
@Override
public int hashCode() {
return toString().hashCode();
}
public InetAddress getLocalInetAddress() {
return localInetAddress;
}
public int getLocalPort() {
return localPort;
}
public InetAddress getRemoteInetAddress() {
return remoteInetAddress;
}
public int getRemotePort() {
return remotePort;
}
public String getTransport() {
return transport;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/TransportManager.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007-2013 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import static net.sourceforge.peers.sip.RFC3261.DEFAULT_SIP_VERSION;
import static net.sourceforge.peers.sip.RFC3261.IPV4_TTL;
import static net.sourceforge.peers.sip.RFC3261.PARAM_MADDR;
import static net.sourceforge.peers.sip.RFC3261.PARAM_TTL;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_DEFAULT_PORT;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_PORT_SEP;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_SCTP;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_TCP;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_TLS_PORT;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_UDP;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_UDP_USUAL_MAX_SIZE;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_VIA_SEP;
import static net.sourceforge.peers.sip.RFC3261.TRANSPORT_VIA_SEP2;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;
import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.Utils;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName;
import net.sourceforge.peers.sip.syntaxencoding.SipHeaders;
import net.sourceforge.peers.sip.syntaxencoding.SipParser;
import net.sourceforge.peers.sip.transaction.TransactionManager;
public class TransportManager {
public static final int SOCKET_TIMEOUT = RFC3261.TIMER_T1;
private static int NO_TTL = -1;
private Logger logger;
//private UAS uas;
private SipServerTransportUser sipServerTransportUser;
protected SipParser sipParser;
private Hashtable<SipTransportConnection, DatagramSocket> datagramSockets;
private Hashtable<SipTransportConnection, MessageSender> messageSenders;
private Hashtable<SipTransportConnection, MessageReceiver> messageReceivers;
private TransactionManager transactionManager;
private Config config;
private int sipPort;
public TransportManager(TransactionManager transactionManager,
Config config, Logger logger) {
sipParser = new SipParser();
datagramSockets = new Hashtable<SipTransportConnection, DatagramSocket>();
messageSenders = new Hashtable<SipTransportConnection, MessageSender>();
messageReceivers = new Hashtable<SipTransportConnection, MessageReceiver>();
this.transactionManager = transactionManager;
this.config = config;
this.logger = logger;
}
public MessageSender createClientTransport(SipRequest sipRequest,
InetAddress inetAddress, int port, String transport)
throws IOException {
return createClientTransport(sipRequest, inetAddress, port, transport,
NO_TTL);
}
public MessageSender createClientTransport(SipRequest sipRequest,
InetAddress inetAddress, int port, String transport, int ttl)
throws IOException {
//18.1
//via created by transaction layer to add branchid
SipHeaderFieldValue via = Utils.getTopVia(sipRequest);
StringBuffer buf = new StringBuffer(DEFAULT_SIP_VERSION);
buf.append(TRANSPORT_VIA_SEP);
if (sipRequest.toString().getBytes().length > TRANSPORT_UDP_USUAL_MAX_SIZE) {
transport = TRANSPORT_TCP;
}
buf.append(transport);
if (inetAddress.isMulticastAddress()) {
SipHeaderParamName maddrName = new SipHeaderParamName(PARAM_MADDR);
via.addParam(maddrName, inetAddress.getHostAddress());
if (inetAddress instanceof Inet4Address) {
SipHeaderParamName ttlName = new SipHeaderParamName(PARAM_TTL);
via.addParam(ttlName, IPV4_TTL);
}
}
//RFC3581
//TODO check config
via.addParam(new SipHeaderParamName(RFC3261.PARAM_RPORT), "");
buf.append(TRANSPORT_VIA_SEP2);//space
//TODO user server connection
InetAddress myAddress = config.getPublicInetAddress();
if (myAddress == null) {
myAddress = config.getLocalInetAddress();
}
buf.append(myAddress.getHostAddress()); //TODO use getHostName if real DNS
buf.append(TRANSPORT_PORT_SEP);
if (sipPort < 1) {
//use default port
if (TRANSPORT_TCP.equals(transport) || TRANSPORT_UDP.equals(transport)
|| TRANSPORT_SCTP.equals(transport)) {
sipPort = TRANSPORT_DEFAULT_PORT;
} else if (TRANSPORT_SCTP.equals(transport)) {
sipPort = TRANSPORT_TLS_PORT;
} else {
throw new RuntimeException("unknown transport type");
}
}
buf.append(sipPort);
//TODO add sent-by (p. 143) Before...
via.setValue(buf.toString());
SipTransportConnection connection = new SipTransportConnection(
config.getLocalInetAddress(), sipPort, inetAddress, port,
transport);
MessageSender messageSender = messageSenders.get(connection);
if (messageSender == null) {
messageSender = createMessageSender(connection);
}
return messageSender;
}
private String threadName(int port) {
return getClass().getSimpleName() + " " + port;
}
public void createServerTransport(String transportType, int port)
throws SocketException {
SipTransportConnection conn = new SipTransportConnection(
config.getLocalInetAddress(), port, null,
SipTransportConnection.EMPTY_PORT, transportType);
MessageReceiver messageReceiver = messageReceivers.get(conn);
if (messageReceiver == null) {
messageReceiver = createMessageReceiver(conn);
new Thread(messageReceiver, threadName(port)).start();
}
if (!messageReceiver.isListening()) {
new Thread(messageReceiver, threadName(port)).start();
}
}
public void sendResponse(SipResponse sipResponse) throws IOException {
//18.2.2
SipHeaderFieldValue topVia = Utils.getTopVia(sipResponse);
String topViaValue = topVia.getValue();
StringBuffer buf = new StringBuffer(topViaValue);
String hostport = null;
int i = topViaValue.length() - 1;
while (i > 0) {
char c = buf.charAt(i);
if (c == ' ' || c == '\t') {
hostport = buf.substring(i + 1);
break;
}
--i;
}
if (hostport == null) {
throw new RuntimeException("host or ip address not found in top via");
}
String host;
int port;
int colonPos = hostport.indexOf(RFC3261.TRANSPORT_PORT_SEP);
if (colonPos > -1) {
host = hostport.substring(0, colonPos);
port = Integer.parseInt(
hostport.substring(colonPos + 1, hostport.length()));
} else {
host = hostport;
port = RFC3261.TRANSPORT_DEFAULT_PORT;
}
String transport;
if (buf.indexOf(RFC3261.TRANSPORT_TCP) > -1) {
transport = RFC3261.TRANSPORT_TCP;
} else if (buf.indexOf(RFC3261.TRANSPORT_UDP) > -1) {
transport = RFC3261.TRANSPORT_UDP;
} else {
logger.error("no transport found in top via header," +
" discarding response");
return;
}
String received =
topVia.getParam(new SipHeaderParamName(RFC3261.PARAM_RECEIVED));
if (received != null) {
host = received;
}
//RFC3581
//TODO check config
String rport = topVia.getParam(new SipHeaderParamName(
RFC3261.PARAM_RPORT));
if (rport != null && !"".equals(rport.trim())) {
port = Integer.parseInt(rport);
}
SipTransportConnection connection;
try {
connection = new SipTransportConnection(config.getLocalInetAddress(),
sipPort, InetAddress.getByName(host),
port, transport);
} catch (UnknownHostException e) {
logger.error("unknwon host", e);
return;
}
//actual sending
//TODO manage maddr parameter in top via for multicast
if (buf.indexOf(RFC3261.TRANSPORT_TCP) > -1) {
// Socket socket = (Socket)factory.connections.get(connection);
// if (!socket.isClosed()) {
// try {
// socket.getOutputStream().write(data);
// } catch (IOException e) {
// e.printStackTrace();
// return;
// //TODO
// }
// } else {
// try {
// socket = new Socket(host, port);
// factory.connections.put(connection, socket);
// socket.getOutputStream().write(data);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// /*
// * TODO
// * If connection attempt fails, use the procedures in RFC3263
// * for servers in order to determine the IP address and
// * port to open the connection and send the response to.
// */
// return;
// }
// }
} else {
MessageSender messageSender = messageSenders.get(connection);
if (messageSender == null) {
messageSender = createMessageSender(connection);
}
//add contact header
SipHeaderFieldName contactName = new SipHeaderFieldName(RFC3261.HDR_CONTACT);
SipHeaders respHeaders = sipResponse.getSipHeaders();
StringBuffer contactBuf = new StringBuffer();
contactBuf.append(RFC3261.LEFT_ANGLE_BRACKET);
contactBuf.append(RFC3261.SIP_SCHEME);
contactBuf.append(RFC3261.SCHEME_SEPARATOR);
contactBuf.append(messageSender.getContact());
contactBuf.append(RFC3261.RIGHT_ANGLE_BRACKET);
respHeaders.add(contactName, new SipHeaderFieldValue(contactBuf.toString()));
messageSender.sendMessage(sipResponse);
}
}
private MessageSender createMessageSender(final SipTransportConnection conn)
throws IOException {
MessageSender messageSender = null;
Object socket = null;
if (RFC3261.TRANSPORT_UDP.equalsIgnoreCase(conn.getTransport())) {
//TODO use Utils.getMyAddress to create socket on appropriate NIC
DatagramSocket datagramSocket = datagramSockets.get(conn);
if (datagramSocket == null) {
logger.debug("new DatagramSocket(" + conn.getLocalPort()
+ ", " + conn.getLocalInetAddress() + ")");
// AccessController.doPrivileged added for plugin compatibility
datagramSocket = AccessController.doPrivileged(
new PrivilegedAction<DatagramSocket>() {
@Override
public DatagramSocket run() {
try {
return new DatagramSocket(conn.getLocalPort(),
conn.getLocalInetAddress());
} catch (SocketException e) {
logger.error("cannot create socket", e);
} catch (SecurityException e) {
logger.error("security exception", e);
}
return null;
}
}
);
if (datagramSocket == null) {
throw new SocketException();
}
datagramSocket.setSoTimeout(SOCKET_TIMEOUT);
datagramSockets.put(conn, datagramSocket);
logger.info("added datagram socket " + conn);
}
socket = datagramSocket;
messageSender = new UdpMessageSender(conn.getRemoteInetAddress(),
conn.getRemotePort(), datagramSocket, config, logger);
} else {
// TODO
// messageReceiver = new TcpMessageReceiver(port);
}
messageSenders.put(conn, messageSender);
//when a mesage is sent over a transport, the transport layer
//must also be able to receive messages on this transport
// MessageReceiver messageReceiver =
// createMessageReceiver(conn, socket);
MessageReceiver messageReceiver = messageReceivers.get(conn);
if (messageReceiver == null) {
messageReceiver = createMessageReceiver(conn, socket);
new Thread(messageReceiver, threadName(conn.getLocalPort())).start();
}
// if (RFC3261.TRANSPORT_UDP.equalsIgnoreCase(conn.getTransport())) {
// messageSender = new UdpMessageSender(conn.getRemoteInetAddress(),
// conn.getRemotePort(), (DatagramSocket)socket, config, logger);
// messageSenders.put(conn, messageSender);
// }
return messageSender;
}
private MessageReceiver createMessageReceiver(SipTransportConnection conn,
Object socket) throws IOException {
MessageReceiver messageReceiver = null;
if (RFC3261.TRANSPORT_UDP.equalsIgnoreCase(conn.getTransport())) {
DatagramSocket datagramSocket = (DatagramSocket)socket;
messageReceiver = new UdpMessageReceiver(datagramSocket,
transactionManager, this, config, logger);
messageReceiver.setSipServerTransportUser(sipServerTransportUser);
}
messageReceivers.put(conn, messageReceiver);
return messageReceiver;
}
private MessageReceiver createMessageReceiver(final SipTransportConnection conn)
throws SocketException {
MessageReceiver messageReceiver = null;
SipTransportConnection sipTransportConnection = conn;
if (RFC3261.TRANSPORT_UDP.equals(conn.getTransport())) {
DatagramSocket datagramSocket = datagramSockets.get(conn);
if (datagramSocket == null) {
logger.debug("new DatagramSocket(" + conn.getLocalPort()
+ ", " + conn.getLocalInetAddress() + ")");
// AccessController.doPrivileged added for plugin compatibility
datagramSocket = AccessController.doPrivileged(
new PrivilegedAction<DatagramSocket>() {
@Override
public DatagramSocket run() {
try {
return new DatagramSocket(conn.getLocalPort(),
conn.getLocalInetAddress());
} catch (SocketException e) {
logger.error("cannot create socket", e);
} catch (SecurityException e) {
logger.error("security exception", e);
}
return null;
}
}
);
datagramSocket.setSoTimeout(SOCKET_TIMEOUT);
if (conn.getLocalPort() == 0) {
sipTransportConnection = new SipTransportConnection(
conn.getLocalInetAddress(),
datagramSocket.getLocalPort(),
conn.getRemoteInetAddress(),
conn.getRemotePort(),
conn.getTransport());
//config.setSipPort(datagramSocket.getLocalPort());
}
sipPort = datagramSocket.getLocalPort();
datagramSockets.put(sipTransportConnection, datagramSocket);
logger.info("added datagram socket " + sipTransportConnection);
}
messageReceiver = new UdpMessageReceiver(datagramSocket,
transactionManager, this, config, logger);
messageReceiver.setSipServerTransportUser(sipServerTransportUser);
//TODO create also tcp receiver using a recursive call
} else {
//TODO
//messageReceiver = new TcpMessageReceiver(port);
}
messageReceivers.put(sipTransportConnection, messageReceiver);
logger.info("added " + sipTransportConnection + ": " + messageReceiver
+ " to message receivers");
return messageReceiver;
}
public void setSipServerTransportUser(
SipServerTransportUser sipServerTransportUser) {
this.sipServerTransportUser = sipServerTransportUser;
}
public void closeTransports() {
for (MessageReceiver messageReceiver: messageReceivers.values()) {
messageReceiver.setListening(false);
}
for (MessageSender messageSender: messageSenders.values()) {
messageSender.stopKeepAlives();
}
try
{
Thread.sleep(SOCKET_TIMEOUT);
}
catch (InterruptedException e)
{
return;
}
// AccessController.doPrivileged added for plugin compatibility
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
@Override
public Void run() {
for (DatagramSocket datagramSocket: datagramSockets.values()) {
datagramSocket.close();
}
return null;
}
}
);
datagramSockets.clear();
messageReceivers.clear();
messageSenders.clear();
}
public MessageSender getMessageSender(
SipTransportConnection sipTransportConnection) {
return messageSenders.get(sipTransportConnection);
}
public int getSipPort() {
return sipPort;
}
public void setSipPort(int sipPort) {
this.sipPort = sipPort;
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/UdpMessageReceiver.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
import net.sourceforge.peers.sip.transaction.TransactionManager;
public class UdpMessageReceiver extends MessageReceiver {
private DatagramSocket datagramSocket;
public UdpMessageReceiver(DatagramSocket datagramSocket,
TransactionManager transactionManager,
TransportManager transportManager, Config config,
Logger logger)
throws SocketException {
super(datagramSocket.getLocalPort(), transactionManager,
transportManager, config, logger);
this.datagramSocket = datagramSocket;
}
@Override
protected void listen() throws IOException {
byte[] buf = new byte[BUFFER_SIZE];
final DatagramPacket packet = new DatagramPacket(buf, buf.length);
final int noException = 0;
final int socketTimeoutException = 1;
final int ioException = 2;
// AccessController.doPrivileged added for plugin compatibility
int result = AccessController.doPrivileged(
new PrivilegedAction<Integer>() {
public Integer run() {
try {
datagramSocket.receive(packet);
} catch (SocketTimeoutException e) {
return socketTimeoutException;
} catch(SocketException e) {
if (e.getMessage().equals("Socket closed") && ! isListening()) // race condition
return noException;
else
return ioException;
} catch (IOException e) {
logger.error("cannot receive packet", e);
return ioException;
}
return noException;
}
});
switch (result) {
case socketTimeoutException:
return;
case ioException:
throw new IOException();
case noException:
break;
default:
break;
}
byte[] trimmedPacket = new byte[packet.getLength()];
System.arraycopy(packet.getData(), 0,
trimmedPacket, 0, trimmedPacket.length);
processMessage(trimmedPacket, packet.getAddress(),
packet.getPort(), RFC3261.TRANSPORT_UDP);
}
}
|
0
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip
|
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/sip/transport/UdpMessageSender.java
|
/*
This file is part of Peers, a java SIP softphone.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2007, 2008, 2009, 2010 Yohann Martineau
*/
package net.sourceforge.peers.sip.transport;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import net.sourceforge.peers.Config;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.sip.RFC3261;
public class UdpMessageSender extends MessageSender {
private DatagramSocket datagramSocket;
public UdpMessageSender(InetAddress inetAddress, int port,
DatagramSocket datagramSocket, Config config,
Logger logger) throws SocketException {
super(datagramSocket.getLocalPort(), inetAddress, port,
config, RFC3261.TRANSPORT_UDP, logger);
this.datagramSocket = datagramSocket;
}
@Override
public synchronized void sendMessage(SipMessage sipMessage) throws IOException {
logger.debug("UdpMessageSender.sendMessage");
if (sipMessage == null) {
return;
}
byte[] buf = sipMessage.toString().getBytes();
sendBytes(buf);
StringBuffer direction = new StringBuffer();
direction.append("SENT to ").append(inetAddress.getHostAddress());
direction.append("/").append(port);
logger.traceNetwork(new String(buf), direction.toString());
}
@Override
public synchronized void sendBytes(byte[] bytes) throws IOException {
logger.debug("UdpMessageSender.sendBytes");
final DatagramPacket packet = new DatagramPacket(bytes, bytes.length,
inetAddress, port);
logger.debug("UdpMessageSender.sendBytes " + bytes.length
+ " " + inetAddress + ":" + port);
// AccessController.doPrivileged added for plugin compatibility
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
@Override
public Void run() {
try {
if (!datagramSocket.isClosed()) {
logger.debug("Local internet-address: " + datagramSocket.getLocalAddress().toString());
datagramSocket.send(packet);
} else {
logger.error("Socket closed. Packet of " + bytes.length + " bytes not sent to " + inetAddress + ":" + port);
}
} catch (Throwable t) {
logger.error("throwable", new Exception(t));
}
return null;
}
}
);
logger.debug("UdpMessageSender.sendBytes packet sent");
}
}
|
0
|
java-sources/ae/teletronics/solr/solr-plugins/0.3/ae/teletronics/solr
|
java-sources/ae/teletronics/solr/solr-plugins/0.3/ae/teletronics/solr/plugin/MemoryInspectorHandler.java
|
package ae.teletronics.solr.plugin;
import org.apache.lucene.index.FilterLeafReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.Accountables;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.metrics.SolrMetricManager;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.util.RefCounted;
import org.apache.solr.util.plugin.SolrCoreAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.util.stream.Collectors;
/**
* This plugin inspects selected parts of a running solr's memory usage. All {@link SolrCore}s in the {@link CoreContainer}
* are inspected, trying to round up {@link Accountable}s. For now, each core gathers the {@link SolrIndexSearcher}s memory usage
* by inspecting the underlying {@link IndexReader}s.
*/
public class MemoryInspectorHandler extends RequestHandlerBase implements SolrCoreAware {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private SolrCore core;
private CoreContainer coreContainer;
@Override
public void handleRequestBody(SolrQueryRequest request, SolrQueryResponse response) {
Accountable memory;
if (coreContainer != null) {
memory = inspectCoreContainer(coreContainer);
if (request.getParams().getBool("dumpToStdOut", false)) {
log.info(Accountables.toString(memory));
}
} else {
memory = () -> 0;
}
Map<String, ?> map = toMap(memory);
response.add("Memory dump", map);
}
private static Map<String, ?> toMap(Accountable accountable) {
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
result.put(accountable.toString(), RamUsageEstimator.humanReadableUnits(accountable.ramBytesUsed(), new DecimalFormat("0.0#", DecimalFormatSymbols.getInstance(Locale.ROOT))));
Collection children = accountable.getChildResources().stream().map(a -> toMap(a)).collect(Collectors.toList());
if (!children.isEmpty()) {
result.put("children", children);
}
return result;
}
private Accountable inspectCoreContainer(CoreContainer coreContainer) {
Collection<SolrCore> cores = (coreContainer.getCores() != null) ? coreContainer.getCores() : Collections.emptyList();
Collection<Accountable> children = cores.stream().map(c -> inspectCore(c)).collect(Collectors.toList());
String name = String.format("Solr cores (count: %s)", children.size());
return Accountables.namedAccountable(name, children, children.stream().mapToLong(Accountable::ramBytesUsed).sum());
}
private Accountable inspectCore(SolrCore core) {
Collection<Accountable> children = new ArrayList<>();
RefCounted<SolrIndexSearcher> searcher = core.getSearcher();
try {
children.add(inspectSearcher(searcher.get()));
} finally {
searcher.decref();
}
String name = String.format("Core '%s' (codec: '%s', lucene match version: '%s')", core.getName(), core.getCodec().getName(), core.getSolrConfig().luceneMatchVersion);
return Accountables.namedAccountable(name, children, children.stream().mapToLong(Accountable::ramBytesUsed).sum());
}
private Accountable inspectSearcher(SolrIndexSearcher searcher) {
Collection<Accountable> children = new ArrayList<>();
children.add(inspectIndexReader(searcher.getIndexReader()));
String name = String.format("Searcher '%s' (numDocs: %s, maxDocs: %s)", searcher.getName(), searcher.numDocs(), searcher.maxDoc());
return Accountables.namedAccountable(name, children, children.stream().mapToLong(Accountable::ramBytesUsed).sum());
}
private Accountable inspectIndexReader(IndexReader indexReader) {
if (indexReader instanceof FilterLeafReader) {
indexReader = FilterLeafReader.unwrap((LeafReader) indexReader);
}
final IndexReader unwrappedReader = indexReader;
Accountable result;
if (indexReader instanceof Accountable) {
result = (Accountable) indexReader;
} else {
if (indexReader.leaves().size() == 0) {
result = Accountables.namedAccountable(unwrappedReader.toString(), 0);
} else {
Collection<Accountable> children = indexReader.leaves().stream().map(lrc -> {
LeafReader reader = lrc.reader();
if (reader == unwrappedReader) {
return Accountables.namedAccountable(unwrappedReader.toString(), 0);
} else {
return inspectIndexReader(reader);
}
}).collect(Collectors.toList());
String name = String.format("IndexReader '%s', segments: %s", indexReader.getClass().getName(), indexReader.leaves().size());
result = Accountables.namedAccountable(name, children, children.stream().mapToLong(Accountable::ramBytesUsed).sum());
}
}
return result;
}
public String getName() {
return "MemoryInspectorHandler";
}
public String getVersion() {
return "1.0";
}
public String getDescription() {
return "Inspects solr memory usage";
}
public Category getCategory() {
return Category.ADMIN;
}
@Override
public void initializeMetrics(SolrMetricManager manager, String registryName, String scope) {
super.initializeMetrics(manager, registryName, scope);
manager.registerGauge(this, registryName, () -> {
return (core != null) ? inspectCore(core).ramBytesUsed() : 0;
}, true, "memoryUsed", new String[]{this.getCategory().toString(), scope});
}
@Override
public void inform(SolrCore solrCore) {
this.core = solrCore;
this.coreContainer = solrCore.getCoreContainer();
}
}
|
0
|
java-sources/ae/teletronics/solr/solr-plugins/0.3/ae/teletronics/solr
|
java-sources/ae/teletronics/solr/solr-plugins/0.3/ae/teletronics/solr/plugin/ThreadRenamingRequestHandler.java
|
package ae.teletronics.solr.plugin;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.metrics.SolrMetricManager;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.util.plugin.SolrCoreAware;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
/**
* This plugin decorates another {@link SolrRequestHandler} and renames the searching thread to
* show the query and the start timestamp. The list of searching threads is exposed as queryhandler
* statistics in the solr admin gui.
*/
public class ThreadRenamingRequestHandler extends RequestHandlerBase implements SolrCoreAware {
private ConcurrentMap<Thread, String> executingThreads = new ConcurrentHashMap<>();
private String delegateName;
private SolrRequestHandler delegate;
public void init(NamedList initArgs) {
delegateName = String.valueOf(initArgs.get("delegate"));
}
public void inform(SolrCore core) {
delegate = core.getRequestHandler(delegateName);
if (delegate == null) {
throw new IllegalArgumentException("Solr request handler delegate not found! Please check your <str name=\"delegate\">...</str> init argument");
}
}
@Override
public void handleRequestBody(SolrQueryRequest solrQueryRequest, SolrQueryResponse solrQueryResponse) {
Thread thread = Thread.currentThread();
String originalThreadName = thread.getName();
try {
try {
executingThreads.put(thread, originalThreadName);
thread.setName(String.format("%s (Start: %s): %s",
delegate.getName(),
DateTimeFormatter.ISO_LOCAL_TIME.format(LocalTime.now()),
SolrParams.toMap(solrQueryRequest.getParams().toNamedList()).toString())
);
} catch (SecurityException | NullPointerException e) {
// Just don't do anything. If we are not allowed to change thread names (or I missed that getParams could be null), we still want to execute the request
}
delegate.handleRequest(solrQueryRequest, solrQueryResponse);
} finally {
executingThreads.remove(thread);
try {
thread.setName(originalThreadName);
} catch (SecurityException e) {
// Yeah, still an issue
}
}
}
public int getRunningRequestCount() {
return executingThreads.size();
}
public List<String> getRunningRequests() {
return executingThreads.keySet().stream().map(Thread::getName).collect(Collectors.toList());
}
public String getName() {
return "ThreadRenamingRequestHandlerDelegate";
}
public String getDescription() {
return "Thread renaming request handler delegate";
}
public Category getCategory() {
return Category.ADMIN;
}
@Override
public void initializeMetrics(SolrMetricManager manager, String registryName, String scope) {
super.initializeMetrics(manager, registryName, scope);
manager.registerGauge(this, registryName, () -> executingThreads.size(), true, "runningRequests", new String[]{this.getCategory().toString(), scope});
}
}
|
0
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/ChangingValueAndLevelMultiCache.java
|
package ae.teletronics.cache;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import net.jcip.annotations.ThreadSafe;
//TODO java8 import java.util.function.Function;
//TODO java8 import java.util.function.Supplier;
//TODO java8 import java.util.function.BiFunction;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.cache.Cache;
/**
* Same as {@link ChangingValueCache}, but with prioritization of the cache-entries. Cache-entries are given a priority (level) and non-overlapping
* intervals of levels define different prioritizations. When a cache-value is modified the level and hence the prioritization of the cache-entry can change
*
* @param <K> Type of the cache-key
* @param <V> Type of the cache-value
*/
@ThreadSafe
public class ChangingValueAndLevelMultiCache<K, V> extends ChangingValueCache<K, V> {
// TODO java8 Remove
public static interface BiFunction<T, U, R> {
R apply(T t, U u);
}
/**
* Builder for building {@link ChangingValueAndLevelMultiCache} instances
*
* @param <K> Type of the cache-key of the built cache
* @param <V> Type of the cache-value of the built cache
*/
public static class Builder<K, V> extends ChangingValueCache.Builder<K, V> {
@Override
protected ChangingValueAndLevelMultiCache<K, V> createInstance() {
return new ChangingValueAndLevelMultiCache<K, V>();
}
private ChangingValueAndLevelMultiCache<K, V> getInstance() {
return (ChangingValueAndLevelMultiCache<K, V>)instance;
}
/**
* See {@link ChangingValueCache.Builder#defaultNewCreator(Supplier)}
*/
public Builder<K, V> defaultNewCreator(Supplier<V> newCreator) {
return (Builder<K, V>)super.defaultNewCreator(newCreator);
}
/**
* See {@link ChangingValueCache.Builder#defaultModifier(Function)}
*/
public Builder<K, V> defaultModifier(Function<V, V> modifier) {
return (Builder<K, V>)super.defaultModifier(modifier);
}
/**
* See {@link ChangingValueCache.Builder#cache(Cache)}. This Guava cache is the internal cache used
* in case a cache-entry has a level that does not fit any of the explicitly defined level-intervals
*/
public Builder<K, V> cache(Cache<K, V> cache) {
return (Builder<K, V>)super.cache(cache);
}
/**
* Set the calculator used to calculate the level of a particular cache-entry
* @param levelCalculator Given the cache-key and cache-level calculate the level of the cache-entry
* @return This builder
*/
public Builder<K,V> levelCalculator(BiFunction<K, V, Integer> levelCalculator) {
getInstance().levelCalculator = levelCalculator;
return this;
}
/**
* Add an additional internal cache to be used for cache-entries with level within a specific interval.
* When a cache-entry is modified so that its level changes to be within levelFrom (inclusive) and
* levelTo (inclusive), the cache-entry will be moved to the provided cache. If when level afterwards
* moves outside the interval, it will be removed from the provided cache and into another internal
* cache - either another cache added using this addCache method, or the default cache
* @param cache The Guava cache to be used internally
* @param levelFrom The lower boundary on cache-entry-level for this cache to be used
* @param levelTo The higher boundary on cache-entry-level for this cache to be used
* @param name A logical name for the cache
* @return This builder
*/
public Builder<K,V> addCache(Cache<K,V> cache, int levelFrom, int levelTo, String name) {
getInstance().caches.put(new Interval(levelFrom, levelTo), cache);
getInstance().names.put(cache, name);
return this;
}
/**
* Build the {@link ChangingValueAndLevelMultiCache} instance
* @return The built {@link ChangingValueAndLevelMultiCache} instance
*/
public ChangingValueAndLevelMultiCache<K,V> build() {
if (getInstance().levelCalculator == null)
throw new RuntimeException("No levelCalculator set");
return (ChangingValueAndLevelMultiCache<K, V>)super.build();
}
}
public static class Interval {
private int from;
private int to;
public Interval(int from, int to) {
this.from = from;
this.to = to;
}
public int getFrom() {
return from;
}
public int getTo() {
return to;
}
public boolean belongsIn(int value) {
return value >= from && value <= to;
}
}
protected Map<Interval, Cache<K, V>> caches = new HashMap<Interval, Cache<K ,V>>();
protected Map<Cache<K, V>, String> names = new HashMap<Cache<K ,V>, String>();
protected BiFunction<K, V, Integer> levelCalculator;
/**
* Get a builder for building a {@link ChangingValueAndLevelMultiCache} instance
*
* @param <K> Type of the cache-key of the built cache
* @param <V> Type of the cache-value of the built cache
*
* @return The builder to be used
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
@Override
protected V modifyImpl(K key, Supplier<V> newCreator, Function<V, V> modifier, boolean createIfNotExists, boolean supportRecursiveCalls) {
V value = alreadyWorkingOn.get();
if (value != null) {
V newValue = ((modifier != null)?modifier:defaultModifier).apply(value);
if (newValue != value) throw new RuntimeException("Modifier called modify with a modifier that replaced value object with another value object");
} else {
Pair<Cache<K, V>, V> cacheAndValue = getCacheAndValueIfPresent(key);
Cache<K, V> oldCache = null;
if (cacheAndValue == null) {
if (createIfNotExists) value = ((newCreator != null)?newCreator:defaultNewCreator).get();
} else {
oldCache = cacheAndValue._1;
value = cacheAndValue._2;
}
if (value != null) {
if (supportRecursiveCalls) alreadyWorkingOn.set(value);
try {
V newValue = ((modifier != null)?modifier:defaultModifier).apply(value);
if (newValue == null) {
if (oldCache != null) oldCache.invalidate(key);
} else {
Cache<K, V> newCache = cacheForLevel(levelCalculator.apply(key, newValue));
if (oldCache != newCache || newValue != value) {
if (oldCache != null && oldCache != newCache) oldCache.invalidate(key);
if (newCache != null) newCache.put(key, newValue);
}
}
value = newValue;
} finally {
if (supportRecursiveCalls) alreadyWorkingOn.remove();
}
}
}
return value;
}
@Override
protected Collection<Cache<K, V>> getAllCaches() {
Collection<Cache<K, V>> allCaches = super.getAllCaches();
for (Cache<K, V> cache : caches.values()) {
allCaches.add(cache);
}
return allCaches;
}
/**
* Get a cache-value and the internal cache it currently lives in of a cache-entry with a provided key
* @param key The key of the cache-entry
* @return The cache-value and the internal cache (or null if not present in cache)
*/
public Pair<Cache<K, V>, V> getCacheAndValueIfPresent(K key) {
for (Cache<K, V> cache : getAllCaches()) {
V value = cache.getIfPresent(key);
if (value != null) return createCacheAndValuePair(cache, value);
}
return null;
}
protected Pair<Cache<K, V>, V> createCacheAndValuePair(Cache<K, V> cache, V value) {
return new Pair<Cache<K, V>, V>(cache, value);
}
protected Cache<K, V> cacheForLevel(int level) {
for (Map.Entry<Interval, Cache<K,V>> entry : caches.entrySet()) {
if (entry.getKey().belongsIn(level)) return entry.getValue();
}
return cache;
}
}
|
0
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/ChangingValueCache.java
|
package ae.teletronics.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import net.jcip.annotations.ThreadSafe;
// TODO java8 import java.util.function.Function;
// TODO java8 import java.util.function.Predicate;
// TODO java8 import java.util.function.Supplier;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.cache.Cache;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
/**
* Key-value cache, where values can change. Several threads can collaborate in building the values. Therefore put operation has been replaced by
* modify operation - knowing about how to create the initial value if the entry is not already present in the cache, and knowing about how to
* modify the value (whether or not it existed in cache already)
*
* @param <K> Type of the cache-key
* @param <V> Type of the cache-value
*/
@ThreadSafe
public class ChangingValueCache<K, V> {
/**
* Builder for building {@link ChangingValueCache} instances
*
* @param <K> Type of the cache-key of the built cache
* @param <V> Type of the cache-value of the built cache
*/
public static class Builder<K, V> {
protected final ChangingValueCache<K, V> instance;
protected Builder() {
instance = createInstance();
}
protected ChangingValueCache<K, V> createInstance() {
return new ChangingValueCache<K, V>();
}
/**
* Set the default new-creator. Used to generate the cache-value, during modify operation when
* * the cache-entry does not already exist
* * and, the modify was not called with an explicit new-creator (overriding this default)
*
* @param newCreator Used to generate the new cache-value
* @return This builder
*/
public Builder<K, V> defaultNewCreator(Supplier<V> newCreator) {
instance.defaultNewCreator = newCreator;
return this;
}
/**
* Set the default modifier. Used to modify the cache-value, during modify operation when
* * the modify was not called with an explicit modifier (overriding this default)
*
* @param modifier Used to modify the cache-value
* @return This builder
*/
public Builder<K, V> defaultModifier(Function<V, V> modifier) {
instance.defaultModifier = modifier;
return this;
}
/**
* The the cache to be used internally
* @param cache The Guava cache to be used internally
* @return This builder
*/
public Builder<K, V> cache(Cache<K, V> cache) {
instance.cache = cache;
return this;
}
/**
* Build the {@link ChangingValueCache} instance
* @return The built {@link ChangingValueCache} instance
*/
public ChangingValueCache<K, V> build() {
if (instance.getAllCaches().size() < 1)
throw new RuntimeException("No inner cache(s) set");
return instance;
}
}
protected Supplier<V> defaultNewCreator;
protected Function<V, V> defaultModifier;
protected Cache<K, V> cache;
protected final Interner<Integer> newOrMovingCacheEntryInterner;
protected ChangingValueCache() {
newOrMovingCacheEntryInterner = Interners.newWeakInterner();
}
/**
* Get a builder for building a {@link ChangingValueCache} instance
*
* @param <K> Type of the cache-key of the built cache
* @param <V> Type of the cache-value of the built cache
*
* @return The builder to be used
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Calling {@link #modify(Object, Supplier, Function, boolean)} (and returning value from) with
* * key (K) Provided key
* * newCreator (Supplier{@literal <V>}) null
* * modifier (Function{@literal <V, V>}) null
* * createIfNotExists (boolean) Provided createIfNotExist
*
* @param key To be forwarded to modify call
* @param createIfNotExists To be forwarded to modify call
* @return The value now on the cache-entry
*/
public final V modify(K key, boolean createIfNotExists) {
return modify(key, null, null, createIfNotExists);
}
/**
* Calling {@link #modify(Object, Supplier, Function, boolean)} (and returning value from) with
* * key (K) Provided key
* * newCreator (Supplier{@literal <V>}) null
* * modifier (Function{@literal <V, V>}) Provided modifier
* * createIfNotExists (boolean) Provided createIfNotExist
*
* @param key To be forwarded to modify call
* @param modifier To be forwarded to modify call
* @param createIfNotExists To be forwarded to modify call
* @return The value now on the cache-entry
*/
public final V modify(K key, Function<V, V> modifier, boolean createIfNotExists) {
return modify(key, null, modifier, createIfNotExists);
}
/**
* Calling {@link #modify(Object, Supplier, Function, boolean)} (and returning value from) with
* * key (K) Provided key
* * newCreator (Supplier{@literal <V>}) Provided new-creator
* * modifier (Function{@literal <V, V>}) null
* * createIfNotExists (boolean) Provided createIfNotExist
*
* @param key To be forwarded to modify call
* @param newCreator To be forwarded to modify call
* @param createIfNotExists To be forwarded to modify call
* @return The value now on the cache-entry
*/
public final V modify(K key, Supplier<V> newCreator, boolean createIfNotExists) {
return modify(key, newCreator, null, createIfNotExists);
}
/**
* Calling {@link #modify(Object, Supplier, Function, boolean, boolean)} (and returning value from) with
* * key (K) Provided key
* * newCreator (Supplier{@literal <V>}) Provided new-creator
* * modifier (Function{@literal <V, V>}) Provided modifier
* * createIfNotExists (boolean) Provided createIfNotExist
* * supportRecursiveCalls (boolean) false
*
* @param key To be forwarded to modify call
* @param newCreator To be forwarded to modify call
* @param modifier To be forwarded to modify call
* @param createIfNotExists To be forwarded to modify call
* @return The value now on the cache-entry
*/
public final V modify(K key, Supplier<V> newCreator, Function<V, V> modifier, boolean createIfNotExists) {
return modify(key, newCreator, modifier, createIfNotExists, false);
}
/**
* Modify cache-entry using provided new-creator and modifier
* @param key Key for cache-entry
* @param newCreator Used to generate the new cache-value, if it does not already exist (if null default new-creator will be used)
* @param modifier Used to modify the cache-value (if null default modifier will be used)
* @param createIfNotExists Create the entry if it does not already exist
* @param supportRecursiveCalls Support modifier that (directly or indirectly) calls modify on THE SAME cache-key (and the same thread).
* Be careful setting this to true
* * Modifier that calls modify on cache-key that is NOT the same will not work correctly - it will when set to false (default)
* * Will add a small performance-hit
* @return The value now on the cache-entry
*/
public final V modify(K key, Supplier<V> newCreator, Function<V, V> modifier, boolean createIfNotExists, boolean supportRecursiveCalls) {
synchronized(newOrMovingCacheEntryInterner.intern(key.hashCode())) {
return modifyImpl(key, newCreator, modifier, createIfNotExists, supportRecursiveCalls);
}
}
/**
* Calling {@link #modifyAll(Predicate, Predicate, Function)} with
* * keyPredicate (Predicate{@literal <K>}) Provided keyPredicate
* * valuePredicate (Predicate{@literal <V>}) Provided valuePredicate
* * modifier (Function{@literal <V, V>}) null
* * supportRecursiveCalls (boolean) false
*
* @param keyPredicate To be forwarded to modifyAll call
* @param valuePredicate To be forwarded to modifyAll call
*/
public final void modifyAll(Predicate<K> keyPredicate, Predicate<V> valuePredicate) {
modifyAll(keyPredicate, valuePredicate, null);
}
/**
* Calling {@link #modifyAll(Predicate, Predicate, Function, boolean)} with
* * keyPredicate (Predicate{@literal <K>}) Provided keyPredicate
* * valuePredicate (Predicate{@literal <V>}) Provided valuePredicate
* * modifier (Function{@literal <V, V>}) Provided modifier
* * supportRecursiveCalls (boolean) false
*
* @param keyPredicate To be forwarded to modifyAll call
* @param valuePredicate To be forwarded to modifyAll call
* @param modifier To be forwarded to modifyAll call
*/
public final void modifyAll(Predicate<K> keyPredicate, Predicate<V> valuePredicate, Function<V, V> modifier) {
modifyAll(keyPredicate, valuePredicate, modifier, false);
}
/**
* Sequentially calling {@link #modify(Object, Supplier, Function, boolean, boolean)} for a selected set of existing cache-entries. Called with
* * key (K) The cache-key of the cache-entry in the selected set
* * newCreator (Supplier{@literal <V>}) null
* * modifier (Function{@literal <V, V>}) Provided modifier
* * boolean createIfNotExists false
* * boolean supportRecursiveCalls Provided supportRecursiveCalls
*
* @param keyPredicate A cache-entry is (potentially - if valuePredicate also accepts) included in the selected set iff feeding keyPredicate with cache-key returns true
* @param valuePredicate A cache-entry is (potentially - if keyPredicate also accepts) included in the selected set iff feeding valuePredicate with cache-value returns true
* @param modifier Used for the modify calls
* @param supportRecursiveCalls Used for the modify calls
*
* The existing cache-entry has to match both criteria to be included in the set
*/
public final void modifyAll(Predicate<K> keyPredicate, Predicate<V> valuePredicate, Function<V, V> modifier, boolean supportRecursiveCalls) {
for (Cache<K, V> cache : getAllCaches()) {
for (Map.Entry<K, V> entry : cache.asMap().entrySet()) {
if ((keyPredicate == null || keyPredicate.apply(entry.getKey())) &&
(valuePredicate == null || valuePredicate.apply(entry.getValue()))) {
modify(entry.getKey(), null, modifier, false, supportRecursiveCalls);
}
}
}
}
protected ThreadLocal<V> alreadyWorkingOn = new ThreadLocal<V>();
protected V modifyImpl(K key, Supplier<V> newCreator, Function<V, V> modifier, boolean createIfNotExists, boolean supportRecursiveCalls) {
V value = alreadyWorkingOn.get();
if (value != null) {
V newValue = ((modifier != null)?modifier:defaultModifier).apply(value);
if (newValue != value) throw new RuntimeException("Modifier called modify with a modifier that replaced value object with another value object");
} else {
value = getIfPresent(key);
boolean created = false;
if (value == null) {
if (createIfNotExists) {
value = ((newCreator != null)?newCreator:defaultNewCreator).get();
created = true;
}
}
if (value != null) {
if (supportRecursiveCalls) alreadyWorkingOn.set(value);
try {
V newValue = ((modifier != null)?modifier:defaultModifier).apply(value);
if (newValue == null) {
cache.invalidate(key);
} else {
if (created || newValue != value) {
cache.put(key, newValue);
}
}
value = newValue;
} finally {
if (supportRecursiveCalls) alreadyWorkingOn.remove();
}
}
}
return value;
}
protected Collection<Cache<K, V>> getAllCaches() {
Collection<Cache<K, V>> allCaches = new ArrayList<Cache<K, V>>();
if (cache != null) {
allCaches.add(cache);
}
return allCaches;
}
/**
* Get a cache-value of a cache-entry with a provided key
* @param key The key of the cache-entry
* @return The cache-value (or null if not present in cache)
*/
public V getIfPresent(K key) {
for (Cache<K, V> cache : getAllCaches()) {
V value = cache.getIfPresent(key);
if (value != null) return value;
}
return null;
}
/**
* @return Number of cache-entries in the cache
*/
public long size() {
long size = 0;
for (Cache<K, V> cache : getAllCaches()) {
size += cache.size();
}
return size;
}
/**
* Calling {@link #getAddIfNotPresent(Object, Supplier)} (and returning value from) with
* * key (K) Provided key
* * newCreator (Supplier{@literal <V>}) null
*
* @param key To be forwarded to getAddIfNotPresent call
* @return The cache-value
*/
public V getAddIfNotPresent(K key) {
return getAddIfNotPresent(key, null);
}
private class NoModificationModifier implements Function<V, V> {
@Override
public V apply(V input) {
return input;
}
}
private NoModificationModifier noModificationModifier = new NoModificationModifier();
/**
* Get a cache-value of a cache-entry with a provided key, adding the cache-entry if not already present
* @param key The key of the cache entry
* @param newCreator Used to generate the new cache-value, if it does not already exist (if null default new-creator will be used)
* @return The cache-value
*/
public V getAddIfNotPresent(K key, Supplier<V> newCreator) {
return modify(key, newCreator, noModificationModifier, true);
}
}
|
0
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/Pair.java
|
package ae.teletronics.cache;
/**
* Just a simple carrier of two objects - for methods parameters and return-values etc.
*
* @param <T1> Type of first in pair
* @param <T2> Type of second in pair
*/
public class Pair<T1, T2> {
public final T1 _1;
public final T2 _2;
public Pair(T1 v1, T2 v2) {
_1 = v1;
_2 = v2;
}
}
|
0
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples/dbversioncache/KeyValueOptimisticLockingDBWithPluggableCache.java
|
package ae.teletronics.cache.examples.dbversioncache;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
public class KeyValueOptimisticLockingDBWithPluggableCache<STOREKEY, STOREVALUE, STOREVALUECONTAINER extends KeyValueOptimisticLockingDBWithPluggableCache.ValueContainer<STOREVALUE>> {
public static class AlreadyExistsException extends Exception {
private static final long serialVersionUID = 1L;
}
public static class DoesNotAlreadyExistException extends Exception {
private static final long serialVersionUID = 1L;
}
public static class VersionConflictException extends Exception {
private static final long serialVersionUID = 1L;
}
public interface ValueContainer<VALUE> extends Cloneable {
void setVersion(Long newVersion);
Long getVersion();
VALUE getValue();
ValueContainer<VALUE> clone();
}
public interface StoreRequest<VALUE, VALUECONTAINER extends ValueContainer<VALUE>> {
enum Operation {
NEW,
UPDATE
}
VALUECONTAINER getValueContainer();
Operation getRequestedOperation();
}
// Pretend that the database actually use a store on disk, making it expensive
// to fetch values
protected ConcurrentMap<STOREKEY, STOREVALUECONTAINER> store = new ConcurrentHashMap<STOREKEY, STOREVALUECONTAINER>();
// Much less expensive to fetch values from cache
protected Cache<STOREKEY, STOREVALUE, STOREVALUECONTAINER> cache;
private final Interner<Integer> keyInterner;
public KeyValueOptimisticLockingDBWithPluggableCache() {
keyInterner = Interners.newWeakInterner();
}
public void initialize(Cache<STOREKEY, STOREVALUE, STOREVALUECONTAINER> cache) {
this.cache = cache;
}
public void put(STOREKEY key, StoreRequest<STOREVALUE, STOREVALUECONTAINER> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
Object synchObject = getSynchObject(key);
if (synchObject != null) {
synchronized(synchObject) {
putImpl(key, storeRequest);
}
} else {
putImpl(key, storeRequest);
}
}
protected Object getSynchObject(STOREKEY key) {
return keyInterner.intern(key.hashCode());
}
protected void putImpl(STOREKEY key, StoreRequest<STOREVALUE, STOREVALUECONTAINER> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
STOREVALUECONTAINER newValue = versionCheck(key, storeRequest);
store.put(key, newValue);
cache.put(key, storeRequest);
}
protected final STOREVALUECONTAINER versionCheck(STOREKEY key, StoreRequest<STOREVALUE, STOREVALUECONTAINER> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
Long currentVersion = getCurrentVersion(key);
if ((storeRequest.getRequestedOperation() == StoreRequest.Operation.NEW) && (currentVersion != null)) {
throw new AlreadyExistsException();
}
if (storeRequest.getRequestedOperation() == StoreRequest.Operation.UPDATE) {
if (currentVersion == null) {
throw new DoesNotAlreadyExistException();
} else if (!storeRequest.getValueContainer().getVersion().equals(currentVersion)) {
throw new VersionConflictException();
}
}
STOREVALUECONTAINER newValue = storeRequest.getValueContainer();
newValue.setVersion((storeRequest.getRequestedOperation() == StoreRequest.Operation.NEW)?0:(newValue.getVersion()+1));
return newValue;
}
public STOREVALUECONTAINER get(STOREKEY key) {
return get(key, true);
}
private STOREVALUECONTAINER get(STOREKEY key, boolean putInCache) {
STOREVALUECONTAINER cacheValue = cache.get(key);
STOREVALUECONTAINER returnValue;
if (cacheValue != null) {
returnValue = cacheValue;
} else {
final STOREVALUECONTAINER storeValue = store.get(key);
if (storeValue != null && putInCache) {
try {
cache.put(key, new StoreRequest<STOREVALUE, STOREVALUECONTAINER>() {
@Override
public STOREVALUECONTAINER getValueContainer() {
return storeValue;
}
@Override
public StoreRequest.Operation getRequestedOperation() {
return StoreRequest.Operation.NEW;
}
});
} catch (Exception e) {
// ignore
}
}
returnValue = storeValue;
}
// Simulate that the client does not receive the same object as the database tries to return to it
// because the object is sent over a network
@SuppressWarnings("unchecked")
STOREVALUECONTAINER clone = (returnValue != null)?(STOREVALUECONTAINER)returnValue.clone():null;
return clone;
}
private Long getCurrentVersion(STOREKEY key) {
Long currentVersion = cache.getVersion(key);
if (currentVersion != null) return currentVersion;
STOREVALUECONTAINER currentValue = get(key, false);
return (currentValue != null)?currentValue.getVersion():null;
}
public interface Cache<STOREKEY, STOREVALUE, STOREVALUECONTAINER extends KeyValueOptimisticLockingDBWithPluggableCache.ValueContainer<STOREVALUE>> {
void put(STOREKEY key, StoreRequest<STOREVALUE, STOREVALUECONTAINER> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException;
STOREVALUECONTAINER get(STOREKEY key);
Long getVersion(STOREKEY key);
}
}
|
0
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples/dbversioncache/StringStringOptimisticLockingDBWithKeyStartsWithCache.java
|
package ae.teletronics.cache.examples.dbversioncache;
import java.util.HashMap;
import java.util.Map;
import ae.teletronics.cache.ChangingValueAndLevelMultiCache;
import ae.teletronics.cache.Pair;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheBuilder;
public class StringStringOptimisticLockingDBWithKeyStartsWithCache extends KeyValueOptimisticLockingDBWithPluggableCache<String, String, StringValueContainer> {
public static class CacheValue {
private boolean complete;
private Map<String, StringValueContainer> keySuffixToValueMap;
public CacheValue() {
complete = false;
keySuffixToValueMap = new HashMap<String, StringValueContainer>();
}
public boolean isComplete() {
return complete;
}
public void setComplete() {
complete = true;
}
public Map<String, StringValueContainer> getKeySuffixToValueMap() {
return keySuffixToValueMap;
}
}
public class KeyStartsWithCache implements Cache<String, String, StringValueContainer> {
private static final String SPLIT = "!";
private final ChangingValueAndLevelMultiCache<String, CacheValue> innerCache;
private KeyStartsWithCache(int cachesSize, int[] levelSplitAfter) {
com.google.common.cache.Cache<String, CacheValue> innerInnerCache = CacheBuilder.newBuilder().maximumSize(cachesSize).build();
ChangingValueAndLevelMultiCache.Builder<String, CacheValue> innerCacheBuilder = ChangingValueAndLevelMultiCache.builder();
innerCacheBuilder
.cache(innerInnerCache)
.defaultModifier(new Function<CacheValue, CacheValue>() {
@Override
public CacheValue apply(CacheValue input) {
return input;
}
})
.levelCalculator(new ChangingValueAndLevelMultiCache.BiFunction<String, CacheValue, Integer>() {
@Override
public Integer apply(String key, CacheValue cacheValue) {
return cacheValue.getKeySuffixToValueMap().size();
}
});
int currentLevelIntervalStart = 0;
for (int currentLevelIntervalEnd : levelSplitAfter) {
innerInnerCache = CacheBuilder.newBuilder().maximumSize(cachesSize).build();
innerCacheBuilder.addCache(innerInnerCache, currentLevelIntervalStart, currentLevelIntervalEnd, "Inner Cache " + currentLevelIntervalStart + "-" + currentLevelIntervalEnd + " size");
currentLevelIntervalStart = currentLevelIntervalEnd+1;
}
innerCache = innerCacheBuilder.build();
}
@Override
public void put(final String key, final StoreRequest<String, StringValueContainer> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
put(key, storeRequest, false);
}
protected void put(final String key, final StoreRequest<String, StringValueContainer> storeRequest, final boolean putInStore) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
try {
final Pair<String, String> splittedKey = splitKey(key);
innerCache.modify(splittedKey._1,
new Supplier<CacheValue>() {
@Override
public CacheValue get() {
return new CacheValue();
}
},
new Function<CacheValue, CacheValue>() {
@Override
public CacheValue apply(CacheValue input) {
try {
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
StringValueContainer newValue = versionCheck(key, storeRequest);
if (putInStore) store.put(key, newValue);
input.getKeySuffixToValueMap().put(splittedKey._2, newValue);
return input;
} catch (Exception e) {
throw (e instanceof RuntimeException)?((RuntimeException)e):new RuntimeException(e);
}
}
}, true);
} catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof AlreadyExistsException) throw (AlreadyExistsException)cause;
if (cause instanceof DoesNotAlreadyExistException) throw (DoesNotAlreadyExistException)cause;
if (cause instanceof VersionConflictException) throw (VersionConflictException)cause;
throw e;
}
}
@Override
public StringValueContainer get(String key) {
final Pair<String, String> splittedKey = splitKey(key);
CacheValue cacheValue = innerCache.getIfPresent(splittedKey._1);
if (cacheValue != null) return cacheValue.getKeySuffixToValueMap().get(splittedKey._2);
return null;
}
@Override
public Long getVersion(String key) {
StringValueContainer valueContainer = get(key);
return (valueContainer != null)?valueContainer.getVersion():null;
}
private Pair<String, String> splitKey(String key) {
int splitIndex = key.indexOf(SPLIT);
if (splitIndex < 0) return new Pair<String, String>(key, null);
return new Pair<String, String>(key.substring(0, splitIndex), key.substring(splitIndex + SPLIT.length()));
}
}
public StringStringOptimisticLockingDBWithKeyStartsWithCache(int cacheSize, int[] levelSplitAfter) {
super();
initialize(new KeyStartsWithCache(cacheSize, levelSplitAfter));
}
@Override
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
protected Object getSynchObject(String key) {
return null;
}
@Override
protected void putImpl(String key, StoreRequest<String, StringValueContainer> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
((KeyStartsWithCache)cache).put(key, storeRequest, true);
}
public Map<String, StringValueContainer> getAllWithKeyStartingWith(final String keyStart) {
CacheValue cacheValue = ((KeyStartsWithCache)cache).innerCache.modify(keyStart,
new Supplier<CacheValue>() {
@Override
public CacheValue get() {
CacheValue newCacheValue = new CacheValue();
newCacheValue.getKeySuffixToValueMap().putAll(getAllFromStore(keyStart, null));
newCacheValue.setComplete();
return newCacheValue;
}
},
new Function<CacheValue, CacheValue>() {
@Override
public CacheValue apply(CacheValue input) {
if (!input.isComplete()) {
input.getKeySuffixToValueMap().putAll(getAllFromStore(keyStart, input.getKeySuffixToValueMap()));
input.setComplete();
}
return input;
}
}, true);
// Simulate that the client does not receive the same object as the database tries to return to it
// because the object is sent over a network
return cloneMapStringStringValueContainer(cacheValue.getKeySuffixToValueMap());
}
private Map<String, StringValueContainer> getAllFromStore(String keyStart, Map<String, StringValueContainer> dontGet) {
Map<String, StringValueContainer> result = new HashMap<String, StringValueContainer>();
for (Map.Entry<String, StringValueContainer> entry : store.entrySet()) {
Pair<String, String> splittedEntryKey = ((KeyStartsWithCache)cache).splitKey(entry.getKey());
if (keyStart.equals(splittedEntryKey._1) && (dontGet == null || !dontGet.containsKey(splittedEntryKey._2))) {
result.put(splittedEntryKey._2, entry.getValue());
}
}
return result;
}
private Map<String, StringValueContainer> cloneMapStringStringValueContainer(Map<String, StringValueContainer> toBeCloned) {
if (toBeCloned == null) return null;
Map<String, StringValueContainer> clone = new HashMap<String, StringValueContainer>(toBeCloned.size());
for (Map.Entry<String, StringValueContainer> entry : toBeCloned.entrySet()) {
clone.put(new String(entry.getKey()), entry.getValue().clone());
}
return clone;
}
}
|
0
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples/dbversioncache/StringStringOptimisticLockingDBWithVersionCache.java
|
package ae.teletronics.cache.examples.dbversioncache;
import ae.teletronics.cache.ChangingValueCache;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheBuilder;
public class StringStringOptimisticLockingDBWithVersionCache extends KeyValueOptimisticLockingDBWithPluggableCache<String, String, StringValueContainer> {
private class VersionCache implements Cache<String, String, StringValueContainer> {
private final ChangingValueCache<String, Long> innerCache;
private VersionCache(int cacheSize) {
com.google.common.cache.Cache<String, Long> innerInnerCache = CacheBuilder.newBuilder().maximumSize(cacheSize).build();
ChangingValueCache.Builder<String, Long> innerCacheBuilder = ChangingValueCache.builder();
innerCache = innerCacheBuilder
.cache(innerInnerCache)
.defaultModifier(new Function<Long, Long>() {
@Override
public Long apply(Long input) {
return input;
}
})
.build();
}
@Override
public void put(final String key, final StoreRequest<String, StringValueContainer> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
put(key, storeRequest, false);
}
protected void put(final String key, final StoreRequest<String, StringValueContainer> storeRequest, final boolean putInStore) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
try {
innerCache.modify(key,
new Supplier<Long>() {
@Override
public Long get() {
return -1L;
}
},
new Function<Long, Long>() {
@Override
public Long apply(Long input) {
try {
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
StringValueContainer newValue = versionCheck(key, storeRequest);
if (putInStore) store.put(key, newValue);
return newValue.getVersion();
} catch (Exception e) {
throw (e instanceof RuntimeException)?((RuntimeException)e):new RuntimeException(e);
}
}
}, true);
} catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof AlreadyExistsException) throw (AlreadyExistsException)cause;
if (cause instanceof DoesNotAlreadyExistException) throw (DoesNotAlreadyExistException)cause;
if (cause instanceof VersionConflictException) throw (VersionConflictException)cause;
throw e;
}
}
@Override
public StringValueContainer get(String key) {
return null;
}
@Override
public Long getVersion(String key) {
return innerCache.getIfPresent(key);
}
}
public StringStringOptimisticLockingDBWithVersionCache(int cacheSize) {
super();
initialize(new VersionCache(cacheSize));
}
@Override
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
protected Object getSynchObject(String key) {
return null;
}
protected void putImpl(String key, StoreRequest<String, StringValueContainer> storeRequest) throws AlreadyExistsException, DoesNotAlreadyExistException, VersionConflictException {
// Taking advantage of the fact that the cache itself is synchronizing on key - usable if we also just add to store in that synch block
((VersionCache)cache).put(key, storeRequest, true);
}
}
|
0
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples
|
java-sources/ae/teletronics/toolbox/cache/0.9/ae/teletronics/cache/examples/dbversioncache/StringValueContainer.java
|
package ae.teletronics.cache.examples.dbversioncache;
public class StringValueContainer implements KeyValueOptimisticLockingDBWithPluggableCache.ValueContainer<String>, Cloneable {
private Long version;
private String text;
public StringValueContainer(Long version, String text) {
this.version = version;
this.text = text;
}
@Override
public void setVersion(Long newVersion) {
version = newVersion;
}
@Override
public Long getVersion() {
return version;
}
@Override
public String getValue() {
return text;
}
@Override
public StringValueContainer clone() {
try {
return (StringValueContainer)super.clone();
} catch (CloneNotSupportedException e) {
// Not gonna happen
return null;
}
}
}
|
0
|
java-sources/aero/albers/osmbse/mdzip-process-sources-maven-plugin/0.0.1/aero/albers
|
java-sources/aero/albers/osmbse/mdzip-process-sources-maven-plugin/0.0.1/aero/albers/osmbse/MdzipProcessSourcesMojo.java
|
package aero.albers.osmbse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
/**
* Processes the sources (a single mdzip) as a mojo
*
*/
@Mojo(name = "mdzip-process-sources", defaultPhase = LifecyclePhase.PROCESS_RESOURCES)
public class MdzipProcessSourcesMojo extends AbstractMojo {
@Parameter(defaultValue = "${project.groupId}", readonly = true)
protected String groupId;
@Parameter(defaultValue = "${project.artifactId}", readonly = true)
protected String artifactId;
@Parameter(defaultValue = "${project.version}", readonly = true)
protected String version;
@Parameter(defaultValue = "${project.build.directory}", readonly = true)
protected File buildDirectory;
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("Processing resources mdzip project: ");
Path baseDir = project.getBasedir().toPath();
getLog().info("Looking for mdzip file");
File origFile;
try {
origFile = Files.walk(baseDir)
.filter(path -> !path.toFile().isDirectory())
.filter(path -> !path.startsWith(baseDir.resolve("target"))) // Exclude the target directory
.filter(path -> path.getFileName().toString().endsWith(".mdzip"))
.map(Path::toFile)
.findFirst()
.orElseThrow(() -> new MojoFailureException("Could not locate .mdzip file"));
} catch (IOException e) {
throw new MojoFailureException("IOException occured while walking directory", e);
}
getLog().info("Copying resources to target directory");
Path targetDir = baseDir.resolve("target");
Path outputFile;
try {
targetDir.toFile().mkdir();
String fname = origFile.getName();
int extension = fname.lastIndexOf('.');
String outFileName = fname.substring(0, extension) + "-" + this.version + fname.substring(extension);
outputFile = targetDir.resolve(outFileName);
Files.copy(origFile.toPath(), outputFile, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new MojoFailureException("Could not copy file to target directory");
}
getLog().info("Setting artifact file");
// this tells maven what the file is that we want to install/deploy
project.getArtifact().setFile(outputFile.toFile());
}
}
|
0
|
java-sources/aero/albers/osmbse/mdzip-validate-maven-plugin/0.0.1/aero/albers
|
java-sources/aero/albers/osmbse/mdzip-validate-maven-plugin/0.0.1/aero/albers/osmbse/MdzipValidateMojo.java
|
package aero.albers.osmbse;
import java.io.File;
import java.nio.file.Path;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
@Mojo(name = "mdzip-validate", defaultPhase = LifecyclePhase.VALIDATE)
public class MdzipValidateMojo extends AbstractMojo {
@Parameter(defaultValue = "${project.groupId}", readonly = true)
private String groupId;
@Parameter(defaultValue = "${project.artifactId}", readonly = true)
private String artifactId;
@Parameter(defaultValue = "${project.version}", readonly = true)
private String version;
@Parameter(defaultValue = "${project.build.directory}", readonly = true)
private File buildDirectory;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("Validating mdzip project: ");
// TODO verify that there's only one cameo file in the project dir
Path baseDir = project.getBasedir().toPath();
//TODO verify that the format of the POM file matches the expected dependencies in the actual mdzip file
}
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/AirlineFlightManifest.java
|
package aero.champ.cargojson.airlineflightmanifest;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.ArrayList;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("An airline flight manifest (FFM) is a notification of details of consigments loaded onto a flight or of details of the onward movement of a consigment loaded.")
public class AirlineFlightManifest {
@JsonProperty(required = true)
@JsonPropertyDescription("The message sequence provides compatibility with Cargo IMP. The first sequence number is '1'.")
public int messageSequence;
@JsonPropertyDescription("Indicated the presence of a related message. That message will contain the next higher sequence number.")
@JsonProperty(required = true)
public boolean hasContinuation;
@JsonProperty(required = true)
public FlightIdAndPointOfLoading flightIdAndPointOfLoading;
@JsonProperty(required = true)
public List<PointOfUnloading> pointOfUnloading = new ArrayList<>();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/AirlineFlightManifestMessage.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.Message;
import aero.champ.cargojson.docgen.annotations.JsonDocHint;
import com.fasterxml.jackson.annotation.JsonClassDescription;
@JsonClassDescription("Cargo Canonical message containing an Airline Flight Manifest as payload.")
@JsonDocHint(toplevel = true)
public class AirlineFlightManifestMessage extends Message<AirlineFlightManifest> {
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/Booking.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.FlightNumber;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;
@JsonClassDescription("Specifies the booked flight")
public class Booking {
@JsonCreator
public Booking(@JsonProperty(value = "flightNumber", required = true) FlightNumber flightNumber, @JsonProperty(value = "dateOfDeparture", required = true) LocalDate dateOfDeparture) {
this.flightNumber = flightNumber;
this.dateOfDeparture = dateOfDeparture;
}
@JsonProperty(required = true)
public final FlightNumber flightNumber;
@JsonProperty(required = true)
public final LocalDate dateOfDeparture;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/Consignment.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.*;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.math.BigInteger;
import java.util.*;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Consignment {
@JsonProperty(required = true)
public AirWaybillNumber airWaybillNumber;
public Optional<OriginAndDestination> originAndDestination = Optional.empty();
@JsonProperty(required = true)
public Quantity quantity;
@JsonProperty(required = true)
public BigInteger totalNumberOfPieces;
public Optional<Volume> volumeDetail = Optional.empty();
public Optional<DensityGroup> densityGroup = Optional.empty();
public Optional<BigInteger> totalConsignmentPieces = Optional.empty();
@JsonProperty(required = true)
public String manifestDescriptionOfGoods;
@JsonPropertyDescription("Array of codes for special handling and dangerous goods.")
public List<SpecialHandlingAndDangerousGoodsCode> specialHandlingAndDangerousGoodsCodes = new ArrayList<>();
@JsonPropertyDescription("Special handling codes that are not covered by the enumeration type of field 'specialHandlingCodes'.")
@JsonDocExample("FOO")
public Set<String> additionalSpecialHandlingCodes = new HashSet<>();
public List<DimensionInfo> dimensionInformation = new ArrayList<>();
public List<RoutingAndBooking> onwardRoutingAndBooking = new ArrayList<>();
public Optional<MovementPriorityCode> movementPriority = Optional.empty();
public List<String> otherServiceInformation = new ArrayList<>();
public Optional<String> customsOriginCode = Optional.empty();
public List<OCI> oci = new ArrayList<>();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/FirstPointOfArrivalInformation.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.IATAAirportCode;
import aero.champ.cargojson.common.ISOCountryCode;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
public class FirstPointOfArrivalInformation {
@JsonProperty(required = true)
public ISOCountryCode isoCountryCode;
@JsonProperty(required = true)
public LocalDateTime scheduleArrival;
@JsonProperty(required = true)
public IATAAirportCode airportCityCode;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/FlightIdAndPointOfLoading.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.Flight;
import aero.champ.cargojson.common.IATAAirportCode;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Describes the flight and the point of unloading")
public class FlightIdAndPointOfLoading {
@JsonProperty(required = true)
public Flight flightIdentification;
@JsonProperty(required = true)
public IATAAirportCode airportCode;
public Optional<String> aircraftRegistration = Optional.empty();
public Optional<FirstPointOfArrivalInformation> firstPointOfArrivalInformation = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/LoadedCargo.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.DimensionInfo;
import aero.champ.cargojson.common.MovementPriorityCode;
import aero.champ.cargojson.common.OCI;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Specifies the consigments loaded, and if no bulk the ULD container containing it")
public class LoadedCargo {
public Optional<ULDInformation> uldInformation = Optional.empty();
@JsonProperty(required = true)
public List<Consignment> consignments = new ArrayList<>();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/PointOfUnloading.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.IATAAirportCode;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Specifies the airpoint of unloading and the respective loaded cargo")
public class PointOfUnloading {
@JsonProperty(required = true)
@JsonPropertyDescription("The airport of unloading")
public IATAAirportCode airportCode;
@JsonPropertyDescription("The date of arrival at the destination")
public Optional<LocalDateTime> dateOfArrival = Optional.empty();
@JsonPropertyDescription("The date of departure at the orifin")
public Optional<LocalDateTime> dateOfDeparture = Optional.empty();
@JsonPropertyDescription("The cargo unloaded at the specified airport")
public List<LoadedCargo> loadedCargo = new ArrayList<>();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/RoutingAndBooking.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.Routing;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class RoutingAndBooking {
public Optional<Routing> routing = Optional.empty();
public Optional<Booking> booking = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airlineflightmanifest/ULDInformation.java
|
package aero.champ.cargojson.airlineflightmanifest;
import aero.champ.cargojson.common.ULD;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class ULDInformation {
@JsonProperty(required = true)
public ULD uld;
public List<RoutingAndBooking> onwardRoutingAndBooking = new ArrayList<>();
public Optional<Integer> percentAvailableVolume = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/AirmailFormat.java
|
package aero.champ.cargojson.airmail;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Andy on 10/17/2017.
*/
public class AirmailFormat {
static HashMap<String, String> messageFunctionCodes = new HashMap<String, String>();
HashMap<String, String> consignorStatusCodes = new HashMap<String, String>();
HashMap<String, String> screeningMethodCodes = new HashMap<String, String>();
HashMap<String, String> screeningExemptionCodes = new HashMap<String, String>();
HashMap<String, String> securityStatusCodes = new HashMap<String, String>();
HashMap<String, String> securityStatusReasons = new HashMap<String, String>();
HashMap<String, String> AR_TransportDirection = new HashMap<String, String>();
HashMap<String, String> AR_BorderAgencyAuthority = new HashMap<String, String>();
HashMap<String, String> AR_Flag = new HashMap<String, String>();
HashMap<String, String> unitQualifier = new HashMap<String, String>();
HashMap<String, String> locationQualifier = new HashMap<String, String>();
HashMap<String, String> codeListResponsibleAgency = new HashMap<String, String>();
HashMap<String, String> codeListQualifier = new HashMap<String, String>();
HashMap<String, String> transportStageQualifier = new HashMap<String, String>();
HashMap<String, String> transportMode = new HashMap<String, String>();
HashMap<String, String> equipmentQualifier = new HashMap<String, String>();
HashMap<String, String> receptacleHandlingClass = new HashMap<String, String>();
public AirmailFormat(){
messageFunctionCodes.put("1", "Cancellation");
messageFunctionCodes.put("4", "Change");
messageFunctionCodes.put("5", "Replace");
messageFunctionCodes.put("6", "Confirmation");
messageFunctionCodes.put("9", "Original");
messageFunctionCodes.put("47", "Definitive");
receptacleHandlingClass.put("R", "Registered items included");
receptacleHandlingClass.put("V", "Screening Exemption");
consignorStatusCodes.put("AC", "Account Consignor");
consignorStatusCodes.put("KC", "Known Consignor");
consignorStatusCodes.put("RA", "Regulated Agent");
screeningMethodCodes.put("PHS", "Physical inspection and/or hand search");
screeningMethodCodes.put("VCK", "Visual check");
screeningMethodCodes.put("XRY", "X-ray equipment");
screeningMethodCodes.put("EDS", "Explosive detection system");
screeningMethodCodes.put("RES", "Remote explosive scent tracing explosive detection dogs");
screeningMethodCodes.put("FRD", "Free running explosive detection dogs");
screeningMethodCodes.put("VPT", "Vapours trace");
screeningMethodCodes.put("PRT", "Particles trace");
screeningMethodCodes.put("MDE", "Metal detection equipment");
screeningMethodCodes.put("SIM", "Subject to flight simulation");
screeningMethodCodes.put("AOM", "Subject to any other means");
screeningExemptionCodes.put("MAIL", "Mail");
securityStatusCodes.put("NSC", "Not secured yet");
securityStatusCodes.put("SPX", "Secured for pasenger flight");
securityStatusCodes.put("SCO", "Secured for all-cargo flight");
securityStatusCodes.put("SHR", "secured for all passenger, all-cargo and all-mail aircraft in accordance with high risk requirements");
securityStatusReasons.put("SE", "Screening Exemption");
securityStatusReasons.put("SM", "Screening Method");
securityStatusReasons.put("CS", "Consignor Status");
AR_TransportDirection.put("1", "Export");
AR_TransportDirection.put("2", "Import");
AR_TransportDirection.put("3", "Transit");
AR_BorderAgencyAuthority.put("CUS", "Customs");
AR_BorderAgencyAuthority.put("AVS", "Aviation security");
AR_BorderAgencyAuthority.put("BOC", "Border control");
AR_BorderAgencyAuthority.put("QRT", "Quarantine");
AR_Flag.put("0", "Advance cargo information required but not provided");
AR_Flag.put("1", "Required advance cargo information has been provided; no response received");
AR_Flag.put("2", "Required advance cargo information has been provided; positive response received");
AR_Flag.put("3", "Advance cargo information has been provided; treat as high risk cargo");
AR_Flag.put("X", "All mail in consignment exempt from advance cargo information");
AR_Flag.put("N", "Advance cargo information not required");
unitQualifier.put("NMB", "Number");
unitQualifier.put("KGM", "Kilogramme");
unitQualifier.put("WT", "Weight");
unitQualifier.put("AAB", "Unit gross weight");
unitQualifier.put("AAL", "Unit net weight");
locationQualifier.put("1", "Place of terms of delivery");
locationQualifier.put("5", "Place of departure");
locationQualifier.put("7", "Place of arrival");
locationQualifier.put("9", "Place of departure. Value accepted for backward compatibility");
locationQualifier.put("13", "Place of arrival. Value accepted for backward compatibility");
locationQualifier.put("84", "Transport contract place of acceptance");
codeListQualifier.put("163", "Country sub-entity");
codeListQualifier.put("102", "Size and type");
codeListQualifier.put("172", "Carrier code");
codeListResponsibleAgency.put("3", "IATA");
codeListResponsibleAgency.put("6", "UN/LOCODE");
codeListResponsibleAgency.put("11", "IATA");
codeListResponsibleAgency.put("13", "Lloyds register of shipping");
codeListResponsibleAgency.put("14", "International chamber of shippoing");
codeListResponsibleAgency.put("20", "BIC");
codeListResponsibleAgency.put("139", "UPU");
codeListResponsibleAgency.put("ZZZ", "Mutually defined");
transportStageQualifier.put("10", "Pre-carriage transport");
transportStageQualifier.put("20", "Main-carriage transport");
transportStageQualifier.put("30", "On-carriage transport");
transportMode.put("1", "Sea");
transportMode.put("2", "Rail");
transportMode.put("3", "Road");
transportMode.put("4", "Air");
equipmentQualifier.put("CN", "Container");
equipmentQualifier.put("UL", "IATA Unit Load Device (air container only");
equipmentQualifier.put("BC", "Aircraft belly cart");
}
public String getMessageFunctionCode(int key){
return messageFunctionCodes.get(String.valueOf(key));
}
public String getConsignorStatusCode(String key){
return consignorStatusCodes.get(key);
}
public String getScreeningMethodCode(String key){
return screeningMethodCodes.get(key);
}
public String getScreeningExemptionCode(String key){
return screeningExemptionCodes.get(key);
}
public String getSecurityStatusCodes(String key){
return securityStatusCodes.get(key);
}
public String getSecurityStatusReason(String key){
return securityStatusReasons.get(key);
}
public String getReceptacleHandlingClass(String key){
return receptacleHandlingClass.get(key);
}
public String getAR_TransportDirection(String key) {
return AR_TransportDirection.get(key);
}
public String getAR_BorderAgencyAuthority(String key){
return AR_BorderAgencyAuthority.get(key);
}
public String getAR_Flag(String key){
return AR_Flag.get(key);
}
public String getUnitQualifier(String key){
return unitQualifier.get(key);
}
public String getLocationQualifier(String key){
return locationQualifier.get(key);
}
public String getCodeListResponsibleAgency(String key){
return codeListResponsibleAgency.get(key);
}
public String getTransportStageQualifier(String key){
return transportStageQualifier.get(key);
}
public String getTransportMode(String key){
return transportMode.get(key);
}
private static String transformPattern(String format) {
String transformedPattern = format.replace("an","[A-Z0-9]");
return transformedPattern;
}
public static void main(String[] args){
// AirmailFormat airmailFormat = new AirmailFormat();
String input = "TDT+40";
String format = "TDT\\+(10|20|30)";
Pattern pattern = Pattern.compile(format);
Matcher m = pattern.matcher(input);
System.out.println("Format := " + pattern.toString());
if(m.matches()){
System.out.println(input + " :- match");
}else{
System.out.println(input + " :- Not match");
}
/*
String in_format = "an{1,12}";
String out_format = "";
if(in_format.contains("an{")){
out_format = in_format.replace("an","[A-Z0-9]");
}else if(in_format.startsWith("a{")){
out_format = in_format.replace("a","[A-Z]");
}
System.out.println("IN : " + in_format);
System.out.println("OUT : " + out_format);
*/
/*
String format = out;
String input = "6";
Pattern pattern = Pattern.compile(format);
Matcher m = pattern.matcher(input);
System.out.println("Format := " + pattern.toString());
if(m.matches()){
System.out.println(input + " :- match");
}else{
System.out.println(input + " :- Not match");
}
*/
}
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/AirmailJsonConverter.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
import java.io.IOException;
/**
* Created by Andy on 09/05/2017.
*/
public class AirmailJsonConverter {
public static void main(String[] args) throws IOException {
/*
AirmailRequest airmail = new AirmailRequest();
ConsignmentInformation consignmentInformation = new ConsignmentInformation();
consignmentInformation.consignmentAddress = "aaa";
ConsignmentSecurityInformation consignmentSecurityInformation = new ConsignmentSecurityInformation();
airmail.consignmentInformation = consignmentInformation;
airmail.consignmentSecurityInformation = consignmentSecurityInformation;
String json = createJsonFormat(airmail);
System.out.println(json);
*/
createSchema();
}
public static void createSchema() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
mapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.registerModule(new Jdk8Module());
JavaTimeModule module = new JavaTimeModule();
mapper.registerModule(module);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
try {
mapper.acceptJsonFormatVisitor(AirmailRequest.class, visitor);
com.fasterxml.jackson.module.jsonSchema.JsonSchema schema = visitor.finalSchema();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public static String createJsonFormat(Object object){
String json = "";
try {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
mapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
mapper.registerModule(new Jdk8Module());
JavaTimeModule module = new JavaTimeModule();
mapper.registerModule(module);
// mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
}catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/AirmailRequest.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class AirmailRequest {
@JsonProperty(required = true)
public ConsignmentInformation consignmentInformation = new ConsignmentInformation();
public ConsignmentSecurityInformation consignmentSecurityInformation = new ConsignmentSecurityInformation();
public Optional<List<ApplicableRegulationInformation>> applicableRegulationInformations = Optional.empty();
public Optional<List<PreConsigningNotificationAuthorityAndRegulation>> preConsigningNotificationAuthorityAndRegulations = Optional.empty();
@JsonProperty(required = true)
public List<TotalsInformation> totalsInformations;
public Optional<HandoverOriginInformation> handoverOriginInformation = Optional.of(new HandoverOriginInformation());
public Optional<HandoverDestinationInformation> handoverDestinationInformation = Optional.of(new HandoverDestinationInformation());
@JsonProperty(required = true)
public List<TransportInformation> transportInformations;
public List<ContainerInformation> containerInformations;
public List<ReceptacleInformation> receptacleInformations;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/AirmailRequestMessage.java
|
package aero.champ.cargojson.airmail;
import aero.champ.cargojson.common.Message;
public class AirmailRequestMessage extends Message<AirmailRequest> {
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ApplicableRegulationInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class ApplicableRegulationInformation {
@JsonProperty(required = true)
public String ARTransportDirection;
@JsonProperty(required = true)
public List<PreConsigningNotificationAuthorityAndRegulation> preConsigningNotificationAuthorityAndRegulations;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ConsignmentInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
public class ConsignmentInformation {
@JsonProperty(required = true)
public String consignmentDocumentNumber; // BGM
@JsonProperty(required = true)
public String messageFunctionCode;
@JsonProperty(required = true)
public String consignmentCategory; // FTX
@JsonProperty(required = true)
public LocalDateTime consignmentCompletionDateTime; // DTM
public String consignmentShipper; // RFF
public String consignmentAddressee; // RFF
public String consignmentContract; // RFF
public String consignmentBillingCarrier; // TDT
public String consignmentPawbNumber; // RFF
public String consignmentOrigin; // RFF ?
public String consignmentDestination; // RFF
public String consignmentPartyToBeInvoiced; // RFF
public String consignmentRouteId;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ConsignmentSecurityInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
import java.util.List;
public class ConsignmentSecurityInformation {
@JsonProperty(required = true)
public String securityStatusCode;
public String securityStatusPartyCode;
public String securityStatusIssuer;
public LocalDateTime securityStatusDateTime; // only apply when code is AIA
public List<SecurityStatusDetailedInformation> securityStatusDetailedInformation;
public List<SecurityTextualStatementInformation> securityTextualStatementInformation;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ConsignorStatus.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ConsignorStatus {
@JsonProperty(required = true)
public String consignorStatusCode;
// if consignor status code is AC, then we have consignor name reference
// else we have consignor id
public String consignorId;
public String consignorNameReference;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ContainerInformation.java
|
package aero.champ.cargojson.airmail;
/**
* Created by Andy on 08/29/2017.
*/
public class ContainerInformation {
public String containerNumber;
public String containerNumberSource;
public String containerEquipmentQualifier;
public String containerType;
public String containerTypeSource;
public double containerWeight;
public String containerWeightType;
public String containerSeal;
public String containerJourneyId;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/HandoverDestinationInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
/**
* Created by Andy on 10/16/2017.
*/
public class HandoverDestinationInformation {
public String handoverDestinationLocationCode;
public String handoverDestinationLocationCodeSource;
public String handoverDestinationLocationName;
@JsonProperty(required = true)
public LocalDateTime handoverDestinationCutOff;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/HandoverOriginInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
public class HandoverOriginInformation {
public String handoverOriginLocationCode;
public String handoverOriginLocationCodeSource;
public String handoverOriginLocationName;
@JsonProperty(required = true)
public LocalDateTime handoverOriginCutOff;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/PreConsigningNotificationAuthorityAndRegulation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PreConsigningNotificationAuthorityAndRegulation {
@JsonProperty(required = true)
public String ARBorderAgencyAuthority;
@JsonProperty(required = true)
public String ARReferenceId;
@JsonProperty(required = true)
public String ARFlag;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ReceptacleInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by Andy on 08/29/2017.
*/
public class ReceptacleInformation {
@JsonProperty(required = true)
public String receptacleType;
@JsonProperty(required = true)
public String receptacleId;
public String receptacleDangerousGoodsIndicator;
public String receptacleHandlingClass;
@JsonProperty(required = true)
public double receptacleWeight;
@JsonProperty(required = true)
public String receptacleWeightType;
public String receptacleContainer;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ScreeningExemption.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ScreeningExemption {
@JsonProperty(required = true)
public String screeningExemptionCode;
@JsonProperty(required = true)
public String screeningExemptionApplicableAuthority;
@JsonProperty(required = true)
public String screeningExemptionApplicableRegulation;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/ScreeningMethod.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ScreeningMethod {
@JsonProperty(required = true)
public String screeningMethodCode;
@JsonProperty(required = true)
public String screeningMethodApplicableAuthority;
@JsonProperty(required = true)
public String screeningMethodApplicableRegulation;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/SecurityStatusDetailedInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SecurityStatusDetailedInformation {
@JsonProperty(required = true)
public String securityStatusReason;
public ConsignorStatus consignorStatus = new ConsignorStatus();
// the following will be stored base on the securityStatusReason
public ScreeningMethod screeningMethod = new ScreeningMethod();
public ScreeningExemption screeningExemption = new ScreeningExemption();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/SecurityTextualStatementInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class SecurityTextualStatementInformation {
@JsonProperty(required = true)
public List<String> consSecurityStatusLine;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/TotalsInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TotalsInformation {
@JsonProperty(required = true)
public String mailClass;
@JsonProperty(required = true)
public int numberOfReceptacles;
@JsonProperty(required = true)
public double weightOfReceptables;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airmail/TransportInformation.java
|
package aero.champ.cargojson.airmail;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
public class TransportInformation {
@JsonProperty(required = true)
public String transportStageQualifier;
public String carrierCode;
public String carrierCodeSource;
public String carrierName;
public String conveyanceReference;
public String modeOfTransport;
public String departureLocationCode;
public String departureLocationCodeSource;
public String departureLocationName;
public LocalDateTime transportDepartureDateTime;
public String arrivalLocationCode;
public String arrivalLocationCodeSource;
public String arrivalLocationName;
public LocalDateTime transportArrivalDateTime;
public String transportLegRateCode;
public String transportLegContract;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/AirWayBill.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.*;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.*;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("An air waybill (AWB) is a receipt issued by an international airline for goods and an evidence of the contract of carriage.")
public class AirWayBill {
@JsonProperty(required = true)
@JsonPropertyDescription("Contains the air waybill number.")
public AirWaybillNumber airWaybillNumber;
@JsonProperty(required = true)
@JsonPropertyDescription("Airport code of origin airport.")
public IATAAirportCode origin;
@JsonProperty(required = true)
@JsonPropertyDescription("Airport code of destination airport.")
public IATAAirportCode destination;
//omit shipment description code as its appearance in cargo imp simply forces you to specify "T" without any extra information
@JsonProperty(required = true)
@JsonPropertyDescription("Total number of pieces of complete consignment.")
@JsonDocExample("20")
public int totalConsignmentNumberOfPieces;
@JsonProperty(required = true)
@JsonPropertyDescription("Weight data of the consignment.")
public Weight weight;
@JsonPropertyDescription("Volume data of the consignment.")
public Optional<Volume> volume = Optional.empty();
@JsonPropertyDescription("Density group - usually given if no volume data is specified.")
public Optional<DensityGroup> densityGroup = Optional.empty();
@JsonPropertyDescription("Flight bookings.")
public Optional<List<Flight>> flights = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("Routing.")
public List<Routing> route = new ArrayList<>();
@JsonProperty(required = true)
@JsonPropertyDescription("Account contact of the shipper.")
public AccountContact shipper;
@JsonProperty(required = true)
@JsonPropertyDescription("Account contact of the consignee.")
public AccountContact consignee;
@JsonProperty(required = true)
@JsonPropertyDescription("Carrier's execution.")
public CarriersExecution carriersExecution;
@JsonProperty(required = true)
@JsonPropertyDescription("Sender reference.")
public ReferenceInfo senderReference;
@JsonProperty(required = true)
@JsonPropertyDescription("Charge Declarations.")
public ChargeDeclarations chargeDeclarations;
@JsonProperty(required = true)
@JsonPropertyDescription("Array of charge items (also known as rate description).")
public List<ChargeItem> chargeItems = new ArrayList<>();
@JsonPropertyDescription("Agent (if Agent entitled to Commission).")
public Optional<AgentIdentification> agent = Optional.empty();
@JsonPropertyDescription("Special Service Request (Information related to instructions for special action required).")
@JsonDocExample("Must be kept above 5 degrees celsius.")
public Optional<String> specialServiceRequest = Optional.empty();
@JsonPropertyDescription("Account contact to be notfied about shipment status changes.")
public Optional<AccountContact> alsoNotify = Optional.empty();
@JsonPropertyDescription("Prepaid charge summary. Though optional, one of prepaid or collect charge summary must be given.")
public Optional<ChargeSummary> prepaidChargeSummary = Optional.empty();
@JsonPropertyDescription("Collect charge summary. Though optional, one of prepaid or collect charge summary must be given.")
public Optional<ChargeSummary> collectChargeSummary = Optional.empty();
@JsonPropertyDescription("Array of codes for special handling and dangerous goods.")
public Set<SpecialHandlingAndDangerousGoodsCode> specialHandlingCodes = new HashSet<>();
@JsonPropertyDescription("Special handling codes that are not covered by the enumeration type of field 'specialHandlingCodes'.")
@JsonDocExample("FOO")
public Set<String> additionalSpecialHandlingCodes = new HashSet<>();
@JsonPropertyDescription("Accounting information.")
public List<Accounting> accounting = new ArrayList<>();
@JsonPropertyDescription("Other charges.")
public List<OtherChargeItem> otherCharges = new ArrayList<>();
@JsonPropertyDescription("Certification of the shipper (name of signature).")
@JsonDocExample("K. Wilson")
public Optional<String> shippersCertification = Optional.empty();
@JsonPropertyDescription("Other service information: Remarks relating to a shipment.")
@JsonDocExample("Extra charge due to special handling requirements.")
public Optional<String> otherServiceInformation = Optional.empty();
@JsonPropertyDescription("Charges Collect in destination currency.")
public Optional<CollectChargesInDestinationCurrency> chargesCollectInDestCurrency = Optional.empty();
@JsonPropertyDescription("Code indicating the origin of goods for Customs purposes.")
@JsonDocExample("T2")
public Optional<String> customsOriginCode = Optional.empty();
@JsonPropertyDescription("Commission information.")
public Optional<CommissionInfo> commissionInfo = Optional.empty();
@JsonPropertyDescription("Sales incentive information.")
public Optional<SalesIncentive> salesIncentive = Optional.empty();
@JsonPropertyDescription("Agent file reference used to identify a specific booking or file.")
@JsonDocExample("123456")
public Optional<String> agentFileReference = Optional.empty();
@JsonPropertyDescription("Nominated handling party.")
public Optional<NominatedHandlingParty> nominatedHandlingParty = Optional.empty();
@JsonPropertyDescription("Shipment reference information.")
public Optional<ShipmentReferenceInfo> shipmentReferenceInformation = Optional.empty();
@JsonPropertyDescription("Array of other participant information.")
public List<OtherParticipant> otherParticipant = new ArrayList<>();
@JsonPropertyDescription("Array of other customs, security and regulatory control information.")
public List<OCI> oci = new ArrayList<>();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/AirWayBillMessage.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.Message;
import aero.champ.cargojson.docgen.annotations.JsonDocHint;
import com.fasterxml.jackson.annotation.JsonClassDescription;
@JsonClassDescription("Cargo Canonical message containing an AirWayBill as payload.")
@JsonDocHint(toplevel = true)
public class AirWayBillMessage extends Message<AirWayBill> {
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/CarriersExecution.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.time.LocalDate;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Carrier's execution.")
public class CarriersExecution {
@JsonProperty(required = true)
@JsonPropertyDescription("Date of Air waybill issue.")
public LocalDate date;
@JsonProperty(required = true)
@JsonPropertyDescription("Location (like 'LONDON') or coded representation of a specific airport/city (like 'LHR').")
@JsonDocExample("LONDON")
public String placeOrAirportCityCode;
@JsonPropertyDescription("Authorisation: Name of signatory.")
@JsonDocExample("K. Wilson")
public Optional<String> authorisationSignature = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/Charge.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.RateClassCode;
import aero.champ.cargojson.common.Weight;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import javax.validation.constraints.Pattern;
import java.math.BigDecimal;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Charge related data.")
public class Charge {
@JsonPropertyDescription("Chargeable weight.")
public Optional<Weight> chargeableWeight = Optional.empty();
@JsonPropertyDescription("Code representing the rate category.")
public Optional<RateClassCode> rateClassCode = Optional.empty();
@JsonPropertyDescription("Code representing the basis rate category.")
public Optional<RateClassCode> rateClassCodeBasis = Optional.empty();
@JsonPropertyDescription("Class rate percentage: A surcharge or discount percentage applied to an applicable rate or charge.")
@JsonDocExample("67")
public Optional<BigDecimal> classRatePercentage = Optional.empty();
@Pattern(regexp = "[0-9][A-Z]{0,2}")
@JsonPropertyDescription("ULD rate class type: Coded description of a Unit Load Device rate class.\n" +
"Must match regular expression '[0-9][A-Z]{0,2}'.")
@JsonDocExample("8")
public Optional<String> uldRateClassType = Optional.empty();
@JsonPropertyDescription("Representation of a rate, charge or discount.")
@JsonDocExample("1234.56")
public Optional<BigDecimal> rateOrCharge = Optional.empty();
@JsonPropertyDescription("Total charge amount.")
@JsonDocExample("2500.00")
public Optional<BigDecimal> totalChargeAmount = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/ChargeDeclarations.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.ChargeCode;
import aero.champ.cargojson.common.PaymentCondition;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.math.BigDecimal;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Charge Declarations.")
public class ChargeDeclarations {
@JsonProperty(required = true)
@JsonPropertyDescription("ISO currency code: Coded representation of a currency approved by ISO.")
@JsonDocExample("GBP")
public String isoCurrencyCode;
@JsonPropertyDescription("Charge Code: Code identifying a method of payment of charges.")
public Optional<ChargeCode> chargeCode = Optional.empty();
@JsonPropertyDescription("Prepaid/Collect indicator for weight valuation.")
public Optional<PaymentCondition> payment_WeightValuation = Optional.empty();
@JsonPropertyDescription("Prepaid/Collect indicator for other charges.")
public Optional<PaymentCondition> payment_OtherCharges = Optional.empty();
@JsonPropertyDescription("Declared value for carriage. The value of a shipment declared for carriage purposes.")
@JsonDocExample("100.00")
public Optional<BigDecimal> declaredValueForCarriage = Optional.empty();
@JsonPropertyDescription("Declared value for customs. The value of a shipment for customs purposes.")
@JsonDocExample("120.00")
public Optional<BigDecimal> declaredValueForCustoms = Optional.empty();
@JsonPropertyDescription("Amount of insurance. The value of a shipment for insurance purposes.")
@JsonDocExample("1000.00")
public Optional<BigDecimal> declaredValueForInsurance = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/ChargeItem.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.ISOCountryCode;
import aero.champ.cargojson.common.ServiceCode;
import aero.champ.cargojson.common.Weight;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Charge item.")
public class ChargeItem {
@JsonPropertyDescription("Number of pieces: Number of loose items and/or ULD's as accepted for carriage.")
@JsonDocExample("8")
public Optional<Integer> numberOfPieces = Optional.empty();
@Pattern(regexp = "[A-Z]{3}")
@JsonPropertyDescription("Rate combination point (RCP): Point over which sector rates are combined.\n" +
"Pattern: uppercase three-letter code.")
@JsonDocExample("PAR")
public Optional<String> rateCombinationPointCityCode = Optional.empty();
@JsonPropertyDescription("Array of commodity item numbers. A commodity item number is to identify a specific commodity.")
@JsonDocExample("9017")
public Optional<Set<String>> commodityItemNumber = Optional.empty();
@JsonPropertyDescription("Chargeable gross weight.")
public Optional<Weight> grossWeight = Optional.empty();
@JsonPropertyDescription("Nature and quantity of goods.")
@JsonDocExample("Tooth paste")
public Optional<String> goodsDescription = Optional.empty();
@JsonPropertyDescription("Toggles whether 'goodsDescription' is contained in the house waybill.")
public boolean consolidation = false;
@JsonPropertyDescription("Array of harmonised commodity codes. A harmonised commodity code is a number " +
"identifying goods for customs or statistical purposes.")
@JsonDocExample("427127829")
public Optional<List<String>> harmonisedCommodityCode = Optional.empty();
@JsonPropertyDescription("Country of origin of goods.")
public Optional<ISOCountryCode> isoCountryCodeOfOriginOfGoods = Optional.empty();
@JsonPropertyDescription("Array of packaging details.")
public Optional<List<Packaging>> packaging = Optional.empty();
@JsonPropertyDescription("Array of charge data.")
public Optional<List<Charge>> charges = Optional.empty();
@JsonPropertyDescription("Service code.")
public Optional<ServiceCode> serviceCode = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/ChargeSummary.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.*;
import java.math.BigDecimal;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Charge Summary - a structure that summarizes charge conditions. " +
"All values are money in an agreed currency.")
public class ChargeSummary {
@JsonPropertyDescription("Charge amount for total weight.")
@JsonDocExample("120.99")
public Optional<BigDecimal> totalWeightCharge = Optional.empty();
@JsonPropertyDescription("Valuation charge amount.")
@JsonDocExample("110.00")
public Optional<BigDecimal> valuationCharge = Optional.empty();
@JsonPropertyDescription("Taxes.")
@JsonDocExample("22.45")
public Optional<BigDecimal> taxes = Optional.empty();
@JsonPropertyDescription("Total other charges due agent.")
@JsonDocExample("32.95")
public Optional<BigDecimal> totalOtherChargesDueAgent = Optional.empty();
@JsonPropertyDescription("Total other charges due carrier.")
@JsonDocExample("43.00")
public Optional<BigDecimal> totalOtherChargesDueCarrier = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("Total charges.")
@JsonDocExample("329.39")
public final BigDecimal chargeSummaryTotal;
@JsonCreator
public ChargeSummary(@JsonProperty(value = "chargeSummaryTotal", required = true) BigDecimal chargeSummaryTotal) {
this.chargeSummaryTotal = chargeSummaryTotal;
}
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/CollectChargesInDestinationCurrency.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.math.BigDecimal;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Charges Collect in destination currency.")
public class CollectChargesInDestinationCurrency {
@JsonProperty(required = true)
@JsonPropertyDescription("ISO currency code of destination currency. Coded representation of a currency approved by ISO.")
@JsonDocExample("GBP")
public String isoCurrencyCode;
@JsonProperty(required = true)
@JsonPropertyDescription("Currency conversion rate: The rate at which one specified currency is expressed in another specified currency.")
@JsonDocExample("2.1512")
public BigDecimal currencyConversionRateOfExchange;
@JsonProperty(required = true)
@JsonPropertyDescription("Collect charges amount in destination currency.")
@JsonDocExample("430.24")
public BigDecimal chargesInDestinationCurrency;
@JsonProperty(required = true)
@JsonPropertyDescription("Charges amount at destination.")
@JsonDocExample("200.00")
public BigDecimal chargesAtDestination;
@JsonProperty(required = true)
@JsonPropertyDescription("Total collect charges amount.")
@JsonDocExample("200.00")
public BigDecimal totalCollectCharges;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/CommissionInfo.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.math.BigDecimal;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Commission information concerning CASS settlement. A CASS settlement factor is a " +
"special rate or charge agreed bilaterally between an " +
"airline and a cargo agent for individual transactions.")
public class CommissionInfo {
@JsonPropertyDescription("Commisson amount CASS settlement factor.")
@JsonDocExample("139")
public Optional<BigDecimal> amountCASSSettlementFactor = Optional.empty();
@JsonPropertyDescription("Percentage CASS settlement factor.")
@JsonDocExample("12")
public Optional<BigDecimal> percentageCASSSettlementFactor = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/EntitlementCode.java
|
package aero.champ.cargojson.airwaybill;
import com.fasterxml.jackson.annotation.JsonClassDescription;
@JsonClassDescription("Entitlement code: Coded identification of the recipient of a charge amount.")
public enum EntitlementCode {
Agent("A"), Carrier("C");
public final String cargoImpCode;
EntitlementCode(String code) { this.cargoImpCode = code; }
public static EntitlementCode fromCode(String code) {
return Agent.cargoImpCode.equals(code) ? Agent : Carrier.cargoImpCode.equals(code) ? Carrier : null;
}
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/NominatedHandlingParty.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
@JsonClassDescription("Nominated handling party.")
public class NominatedHandlingParty {
@JsonProperty(required = true)
@JsonPropertyDescription("Identification of individual or company involved in the movement of a consignment.")
@JsonDocExample("ACE Shipping Co.")
public final String name;
@JsonProperty(required = true)
@JsonPropertyDescription("Location of individual or company involved in the movement of a consignment.")
@JsonDocExample("London")
public final String place;
@JsonCreator
public NominatedHandlingParty(@JsonProperty(required = true,value = "name")
String name,
@JsonProperty(required = true,value = "place")
String place) {
this.name = name;
this.place = place;
}
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/OtherChargeItem.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.OtherChargeCode;
import aero.champ.cargojson.common.PaymentCondition;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.math.BigDecimal;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Structure for other charge items.")
public class OtherChargeItem {
@JsonProperty(required = true)
@JsonPropertyDescription("Prepaid/Collect indicator.")
public PaymentCondition paymentCondition;
@JsonProperty(required = true)
@JsonPropertyDescription("Other charge code.")
public OtherChargeCode otherChargeCode;
@JsonProperty(required = true)
@JsonPropertyDescription("Entitlement code.")
public EntitlementCode entitlementCode;
@JsonProperty(required = true)
@JsonPropertyDescription("Charge amount (money).")
@JsonDocExample("120.46")
public BigDecimal chargeAmount;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/OtherParticipant.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.OfficeMessageAddress;
import aero.champ.cargojson.common.ParticipantIdentifier;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Other participant information.")
public class OtherParticipant {
@JsonProperty(required = true)
@JsonPropertyDescription("Identification of individual or company involved in the movement of a consignment.")
@JsonDocExample("ACE Shipping Co.")
public String name;
@JsonPropertyDescription("Other participant office message address.")
public Optional<OfficeMessageAddress> officeMessageAddress = Optional.empty();
@JsonPropertyDescription("Other participant office file reference.")
@JsonDocExample("123456")
public Optional<String> fileReference = Optional.empty();
@JsonPropertyDescription("Other participant identification.")
public Optional<ParticipantIdentifier> participantIdentification = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/Packaging.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.Dimensions;
import aero.champ.cargojson.common.ULD;
import aero.champ.cargojson.common.Volume;
import aero.champ.cargojson.common.Weight;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Packaging details of goods. The fields are optional, but at least one should be filled.")
public class Packaging {
@JsonPropertyDescription("Number of pieces: Number of loose items and/or ULD's as accepted for carriage.")
@JsonDocExample("8")
public Optional<Integer> numberOfPieces = Optional.empty();
@JsonPropertyDescription("Weight of the goods.")
public Optional<Weight> weight = Optional.empty();
@JsonPropertyDescription("Volume of the goods.")
public Optional<Volume> volume = Optional.empty();
@JsonPropertyDescription("Dimensions of the goods.")
public Optional<Dimensions> dimensions = Optional.empty();
@JsonPropertyDescription("Unit Load Device (ULD) data.")
public Optional<ULD> uld = Optional.empty();
@JsonPropertyDescription("Shipper's load and count.")
@JsonDocExample("15000")
public Optional<Integer> shippersLoadAndCount = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/SalesIncentive.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.CASSIndicator;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.math.BigDecimal;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Sales incentive information.")
public class SalesIncentive {
@JsonProperty(required = true)
@JsonPropertyDescription("Sales incentive charge amount.")
@JsonDocExample("20.00")
public BigDecimal chargeAmount;
@JsonPropertyDescription("CASS Indicator.")
public Optional<CASSIndicator> cassIndicator = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/airwaybill/TransportEquipment.java
|
package aero.champ.cargojson.airwaybill;
import aero.champ.cargojson.common.ULD;
import aero.champ.cargojson.common.Volume;
import aero.champ.cargojson.common.Weight;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Optional;
public class TransportEquipment {
@JsonProperty(required = true)
public int shippersLoadAndCount;
//TODO: does the weight and volume declare the volume of one piece or the sum of all pieces?
public Optional<Weight> totalWeight = Optional.empty();
public Optional<Volume> totalVolume = Optional.empty();
public Optional<ULD> uld = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/common/AccountContact.java
|
package aero.champ.cargojson.common;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.List;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Contact data of an account (for example for a shipper or a consignee.")
public class AccountContact {
@JsonPropertyDescription("Account number (coded identification of a participant).")
@JsonDocExample("ABC94269")
public Optional<String> accountNumber = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("Address of the contact.")
public Address address;
@JsonPropertyDescription("Further contact details.")
public Optional<List<ContactDetail>> contactDetails = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/common/Accounting.java
|
package aero.champ.cargojson.common;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Accounting information")
public class Accounting {
@JsonProperty(required = true)
@JsonPropertyDescription("Accounting Information Identifier (code indicating a specific kind of accounting information).")
@JsonDocExample("GovernmentBillOfLading")
public AccountingInformationIdentifier identifier;
@JsonProperty(required = true)
@JsonPropertyDescription("Detail of accounting information ")
@JsonDocExample("Payment by certified cheque.")
public String accountingInformation;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/common/AccountingInformationIdentifier.java
|
package aero.champ.cargojson.common;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.stream.Stream;
@JsonFormat(shape = JsonFormat.Shape.STRING)
@JsonClassDescription("Accounting information identifier enumeration. Code indicating a specific kind of accounting information.")
public enum AccountingInformationIdentifier {
CreditCardNumber("CRN"),
CreditCardExpiryDate("CRD"),
CreditCardIssuanceName("CRI"),
GeneralInformation("GEN"),
GovernmentBillOfLading("GBL"),
MiscellaneousChargeOrder("MCO"),
ModeOfSettlement("STL"),
ReturnToOrigin("RET"),
ShippersReferenceNumber("SRN");
public final String cargoImpCode;
AccountingInformationIdentifier(String cargoImpCode) {
this.cargoImpCode = cargoImpCode;
}
public static AccountingInformationIdentifier fromCargoImp(String cargoImpCode) {
return Stream.of(values()).filter(v->v.cargoImpCode.equals(cargoImpCode)).findFirst().get();
}
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/common/Address.java
|
package aero.champ.cargojson.common;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import javax.xml.bind.annotation.XmlAttribute;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Postal address of an individual or a company.")
public class Address {
@XmlAttribute
@JsonProperty(required = true)
@JsonPropertyDescription("First and mandatory name field.")
@JsonDocExample("Donald Trump")
public String name1;
@JsonPropertyDescription("Optional second name field.")
@JsonDocExample("President of the United States of America")
public Optional<String> name2 = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("First and mandatory street field.")
@JsonDocExample("The White House")
public String streetAddress1;
@JsonPropertyDescription("Optional second street field.")
@JsonDocExample("1600 Pennsylvania Avenue NW")
public Optional<String> streetAddress2 = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("Location or place of the address.")
@JsonDocExample("Washington, DC")
public String place;
@JsonPropertyDescription("Part of a country.")
@JsonDocExample("DC")
public Optional<String> stateProvince = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("ISO Country Code of the address.")
public ISOCountryCode country;
@JsonProperty(required = true)
@JsonPropertyDescription("Postal code of the address.")
@JsonDocExample("20500")
public String postCode;
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/common/Addressing.java
|
package aero.champ.cargojson.common;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Addressing data of a Cargo Canonical Message.")
public class Addressing {
@JsonPropertyDescription("Participant address the message shall be sent via.")
public Optional<ParticipantAddress> routeVia = Optional.empty();
@JsonPropertyDescription("Participant address an answer to the message shall be sent via.")
public Optional<ParticipantAddress> routeAnswerVia = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("Array of addresses of the sender of the message.")
public List<ParticipantAddress> senderAddresses = new ArrayList<>();
@JsonProperty(required = true)
@JsonPropertyDescription("Array of addresses of the final recipients.")
public List<ParticipantAddress> finalRecipientAddresses = new ArrayList<>();
@JsonPropertyDescription("Array of addresses that shall be used to deliver replies to the message.")
public List<ParticipantAddress> replyAnswerTo = new ArrayList<>();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/common/Agent.java
|
package aero.champ.cargojson.common;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Agent {
@JsonProperty(required = true)
@JsonPropertyDescription("Name of the agent")
public String name;
@JsonProperty(required = true)
public String place;
public Optional<String> accountNumber = Optional.empty();
public Optional<String> iataCargoAgentNumericCode = Optional.empty();
public Optional<String> iataCargoAgentCASSAddress = Optional.empty();
public Optional<String> participantIdentifier = Optional.empty();
}
|
0
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson
|
java-sources/aero/champ/cargojson/1.0/aero/champ/cargojson/common/AgentIdentification.java
|
package aero.champ.cargojson.common;
import aero.champ.cargojson.docgen.annotations.JsonDocExample;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import java.util.Optional;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonClassDescription("Identifies an agent.")
public class AgentIdentification {
@JsonProperty(required = true)
@JsonPropertyDescription("Identification of individual or company.")
@JsonDocExample("ACE SHIPPING CO.")
public String name;
@JsonProperty(required = true)
@JsonPropertyDescription("Location of individual or company")
@JsonDocExample("LONDON")
public String place;
@JsonPropertyDescription("Coded identification of a participant.")
@JsonDocExample("ABC94269")
public Optional<String> accountNumber = Optional.empty();
@JsonProperty(required = true)
@JsonPropertyDescription("IATA Cargo Agent Numeric Code (code issued by IATA to identify " +
"each IATA Cargo Agent whose name is entered on the Cargo Agency List).")
@JsonDocExample("1234567")
public String iataCargoAgentNumericCode;
@JsonPropertyDescription("IATA Cargo Agent CASS Address (" +
"code issued by IATA to identify individual agent locations for CASS billing purposes).")
@JsonDocExample("1234")
public Optional<String> iataCargoAgentCASSAddress = Optional.empty();
@JsonPropertyDescription("Participant Identifier: Code identifying the type of participant involved in the movement of a shipment.")
@JsonDocExample("CNE")
public Optional<String> participantIdentifier = Optional.empty();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.