Search in sources :

Example 11 with ParseException

use of java.text.ParseException in project Openfire by igniterealtime.

the class Recorder method getAbsolutePath.

public static String getAbsolutePath(String recordDirectory, String recordPath) throws IOException {
    String osName = System.getProperty("os.name");
    if (osName.indexOf("Windows") >= 0) {
        if (recordPath.substring(0, 1).equals(fileSeparator) == true || recordPath.charAt(1) == ':') {
            return recordPath;
        }
    } else {
        if (recordPath.substring(0, 1).equals(fileSeparator) == true) {
            return recordPath;
        }
    }
    /*
	 * Not absolute
	 */
    if (recordDirectory == null) {
        recordDirectory = System.getProperty("com.sun.voip.server.Bridge.recordDirectory", defaultRecordDirectory);
    }
    String path = recordDirectory + fileSeparator + recordPath;
    try {
        checkPermission(path, false);
    } catch (ParseException e) {
        throw new IOException(e.getMessage());
    }
    return recordDirectory + fileSeparator + recordPath;
}
Also used : ParseException(java.text.ParseException) IOException(java.io.IOException)

Example 12 with ParseException

use of java.text.ParseException in project Openfire by igniterealtime.

the class Recorder method checkPermission.

public static void checkPermission(String recordPath, boolean isDirectory) throws ParseException {
    if (isDirectory) {
        File file = new File(recordPath);
        if (file.exists() == false) {
            throw new ParseException("Non-existent directory:  " + recordPath, 0);
        }
        if (file.isDirectory() == false) {
            throw new ParseException("Not a directory:  " + recordPath, 0);
        }
        if (file.canWrite() == false) {
            throw new ParseException("Permission denied.  Can't write " + recordPath, 0);
        }
        return;
    }
    File file = new File(recordPath);
    try {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new ParseException("Not a regular file:  " + recordPath + ".", 0);
            }
        }
        /*
	     * Try to create a file in the directory
	     */
        String directory = defaultRecordDirectory;
        int i = recordPath.lastIndexOf(fileSeparator);
        if (i > 0) {
            directory = recordPath.substring(0, i);
        }
        file = File.createTempFile("Record", "tmp", new File(directory));
        file.delete();
    } catch (IOException e) {
        throw new ParseException("Unable to create file " + recordPath + ".  " + e.getMessage(), 0);
    }
}
Also used : ParseException(java.text.ParseException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 13 with ParseException

use of java.text.ParseException in project Openfire by igniterealtime.

the class RtpmapParser method parseSdp.

public synchronized SdpInfo parseSdp(String sdpData) throws ParseException {
    /*
	 * parse sdpData
	 */
    String t = "c=IN IP4 ";
    int start = sdpData.indexOf(t);
    int finish = sdpData.indexOf("\r", start);
    if (start < 0 || finish < 0) {
        throw new ParseException("Invalid remote SDP", 0);
    }
    String remoteHost = sdpData.substring(start + t.length(), finish).trim();
    t = "m=audio";
    start = sdpData.indexOf(t);
    String s = sdpData.substring(start + t.length());
    t = "RTP/AVP ";
    finish = s.indexOf(t);
    String port = s.substring(0, finish).trim();
    if (start < 0 || finish < 0) {
        throw new ParseException("Invalid remote SDP", 0);
    }
    int remotePort;
    try {
        remotePort = Integer.parseInt(port);
    } catch (NumberFormatException e) {
        Logger.println("Invalid remote port in sdp " + port + " sdpData " + sdpData);
        throw new ParseException("Invalid remote port in sdp " + port + " sdpData " + sdpData, 0);
    }
    start = finish + t.length();
    finish = s.indexOf("\r\n");
    // point at payloads
    s = s.substring(start, finish);
    /*
	 * Get all supported RTP Payloads
	 */
    String[] payloads = s.split("[\" \"]");
    String[] sdp = sdpData.split("[\r\n]");
    MediaInfo mediaInfo = new MediaInfo(RtpPacket.PCMU_PAYLOAD, 0, 8000, 1, false);
    // we always support payload 0
    supportedMedia.add(mediaInfo);
    byte telephoneEventPayload = 0;
    /*
	 * Get all "a=rtpmap:" entries, stop when we hit a non-rtpmap entry
	 */
    for (int i = 0; i < sdp.length; i++) {
        s = sdp[i];
        if (s.indexOf("a=rtpmap:") != 0) {
            continue;
        }
        RtpmapParser rtpmapParser = new RtpmapParser(s);
        mediaInfo = rtpmapParser.getMediaInfo();
        if (mediaInfo == null) {
            // skip this entry
            continue;
        }
        if (mediaInfo.isTelephoneEventPayload()) {
            telephoneEventPayload = mediaInfo.getPayload();
        }
        supportedMedia.add(mediaInfo);
    }
    /*
	 * At this point, payloads[] contains all of the supported payloads
	 * and the Vector supportedMedia contains the MediaInfo's for
	 * all supported payloads.
	 *
	 * For each payload, find the corresponding MediaInfo and
         * select the appropriate one.
	 */
    mediaInfo = null;
    boolean preferredMediaSpecified = false;
    t = "a=PreferredPayload:";
    if ((start = sdpData.indexOf(t)) >= 0) {
        s = sdpData.substring(start + t.length());
        finish = s.indexOf("\r\n");
        if (finish > 0) {
            int payload;
            s = s.substring(0, finish);
            payload = Integer.parseInt(s);
            try {
                mediaInfo = getMediaInfo(payload);
            } catch (ParseException e) {
            }
            preferredMediaSpecified = true;
        }
    }
    if (mediaInfo == null) {
        for (int i = 0; i < payloads.length; i++) {
            int payload = 0;
            try {
                payload = Integer.parseInt(payloads[i]);
            } catch (NumberFormatException e) {
                Logger.println("Invalid payload in rtpmap: " + payloads[i]);
                throw new ParseException("Invalid payload int rtpmap: " + payloads[i], 0);
            }
            if (payload != 0 && (payload < 96 || payload > 127)) {
                /*
		     * Not one we can deal with
		     */
                continue;
            }
            /*
	         * See if it's a supported payload
	         */
            MediaInfo m = null;
            try {
                m = getMediaInfo(payload);
            } catch (ParseException e) {
                Logger.println("ignoring undefined payload " + payload);
                continue;
            }
            if (m.isTelephoneEventPayload()) {
                continue;
            }
            if (mediaInfo == null || mediaInfo.getSampleRate() < m.getSampleRate()) {
                mediaInfo = m;
            } else if (mediaInfo.getSampleRate() == m.getSampleRate()) {
                if (mediaInfo.getChannels() < m.getChannels()) {
                    mediaInfo = m;
                }
            }
        }
    }
    if (mediaInfo == null) {
        Logger.println("No suitable media payload in sdp data " + sdpData);
        throw new ParseException("No suitable media payload in sdp data " + sdpData, 0);
    }
    sdpInfo = new SdpInfo(remoteHost, remotePort, telephoneEventPayload, supportedMedia, mediaInfo, preferredMediaSpecified);
    t = "a=transmitPayload:";
    if ((start = sdpData.indexOf(t)) >= 0) {
        s = sdpData.substring(start + t.length());
        finish = s.indexOf("\r\n");
        if (finish > 0) {
            int payload;
            s = s.substring(0, finish);
            payload = Integer.parseInt(s);
            try {
                sdpInfo.setTransmitMediaInfo(getMediaInfo(payload));
                Logger.println("Set xmit mediaInfo to " + sdpInfo.getTransmitMediaInfo());
            } catch (ParseException e) {
            }
        }
    }
    int ix;
    t = "a=transmitMediaInfoOk";
    if ((ix = sdpData.indexOf(t)) >= 0) {
        sdpInfo.setTransmitMediaInfoOk(true);
    }
    t = "a=userName:";
    if ((ix = sdpData.indexOf(t)) >= 0) {
        String userName = sdpData.substring(ix + t.length());
        finish = userName.indexOf("\n");
        if (finish > 0) {
            sdpInfo.setUserName(userName.substring(0, finish).trim());
        } else {
            /*
                 * This is a workaround for a bug where "\r\n" are missing
                 * from the SDP.
                 * XXX This assumes "userName:" is last in the sdp.
                 */
            sdpInfo.setUserName(userName.substring(0).trim());
        }
    }
    t = "a=callId:";
    if ((ix = sdpData.indexOf(t)) >= 0) {
        String callId = sdpData.substring(ix + t.length());
        finish = callId.indexOf("\n");
        if (finish > 0) {
            sdpInfo.setCallId(callId.substring(0, finish).trim());
        }
    }
    t = "a=conferenceId:";
    if ((ix = sdpData.indexOf(t)) >= 0) {
        String conferenceId = sdpData.substring(ix + t.length());
        finish = conferenceId.indexOf("\n");
        if (finish > 0) {
            sdpInfo.setConferenceId(conferenceId.substring(0, finish).trim());
        } else {
            /*
		 * This is a workaround for a bug where "\r\n" are missing
		 * from the SDP.
		 * XXX This assumes "conferenceId:" is last in the sdp.
		 */
            sdpInfo.setConferenceId(conferenceId.substring(0).trim());
        }
    }
    if (sdpData.indexOf("a=distributedBridge") >= 0) {
        sdpInfo.setDistributedBridge();
    }
    t = "a=rtcpAddress:";
    if ((ix = sdpData.indexOf(t)) >= 0) {
        s = sdpData.substring(ix + t.length());
        finish = s.indexOf("\n");
        if (finish > 0) {
            s = s.substring(0, finish).trim();
        } else {
            s = s.substring(0).trim();
        }
        String[] tokens = s.split(":");
        if (tokens.length != 2) {
            throw new ParseException("Invalid rtcp address in sdp " + " sdpData " + sdpData, 0);
        }
        try {
            sdpInfo.setRtcpAddress(new InetSocketAddress(InetAddress.getByName(tokens[0]), Integer.parseInt(tokens[1])));
        } catch (UnknownHostException e) {
            throw new ParseException("Invalid rtcp host address in sdp " + " sdpData " + sdpData, 0);
        } catch (NumberFormatException e) {
            throw new ParseException("Invalid rtcp port in sdp " + " sdpData " + sdpData, 0);
        }
    }
    return sdpInfo;
}
Also used : UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) ParseException(java.text.ParseException)

Example 14 with ParseException

use of java.text.ParseException in project Openfire by igniterealtime.

the class SipSecurityManager method handleChallenge.

/**
     * Uses securityAuthority to determinie a set of valid user credentials for
     * the specified Response (Challenge) and appends it to the challenged
     * request so that it could be retransmitted.
     * <p/>
     * Fredrik Wickstrom reported that dialog cseq counters are not incremented
     * when resending requests. He later uncovered additional problems and
     * proposed a way to fix them (his proposition was taken into account).
     *
     * @param challenge             the 401/407 challenge response
     * @param challengedTransaction the transaction established by the challenged request
     * @return a transaction containing a reoriginated request with the
     *         necessary authorization header.
     * @throws SipSecurityException
     */
public ClientTransaction handleChallenge(Response challenge, ClientTransaction challengedTransaction) throws SipSecurityException, SipException, InvalidArgumentException, ParseException {
    try {
        String branchID = challengedTransaction.getBranchId();
        Request challengedRequest = challengedTransaction.getRequest();
        Request reoriginatedRequest = (Request) challengedRequest.clone();
        ListIterator authHeaders = null;
        if (challenge == null || reoriginatedRequest == null)
            throw new NullPointerException("A null argument was passed to handle challenge.");
        if (challenge.getStatusCode() == Response.UNAUTHORIZED)
            authHeaders = challenge.getHeaders(WWWAuthenticateHeader.NAME);
        else if (challenge.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED)
            authHeaders = challenge.getHeaders(ProxyAuthenticateHeader.NAME);
        if (authHeaders == null)
            throw new SecurityException("Could not find WWWAuthenticate or ProxyAuthenticate headers");
        // Remove all authorization headers from the request (we'll re-add
        // them
        // from cache)
        reoriginatedRequest.removeHeader(AuthorizationHeader.NAME);
        reoriginatedRequest.removeHeader(ProxyAuthorizationHeader.NAME);
        // rfc 3261 says that the cseq header should be augmented for the
        // new
        // request. do it here so that the new dialog (created together with
        // the new client transaction) takes it into account.
        // Bug report - Fredrik Wickstrom
        CSeqHeader cSeq = (CSeqHeader) reoriginatedRequest.getHeader((CSeqHeader.NAME));
        cSeq.setSequenceNumber(cSeq.getSequenceNumber() + 1);
        ClientTransaction retryTran = transactionCreator.getNewClientTransaction(reoriginatedRequest);
        WWWAuthenticateHeader authHeader = null;
        CredentialsCacheEntry ccEntry = null;
        while (authHeaders.hasNext()) {
            authHeader = (WWWAuthenticateHeader) authHeaders.next();
            String realm = authHeader.getRealm();
            // Check whether we have cached credentials for authHeader's
            // realm
            // make sure that if such credentials exist they get removed.
            // The
            // challenge means that there's something wrong with them.
            ccEntry = cachedCredentials.remove(realm);
            // Try to guess user name and facilitate user
            UserCredentials defaultCredentials = new UserCredentials();
            FromHeader from = (FromHeader) reoriginatedRequest.getHeader(FromHeader.NAME);
            URI uri = from.getAddress().getURI();
            if (uri.isSipURI()) {
                Log.debug("handleChallenge", SIPConfig.getAuthUserName());
                String user = SIPConfig.getAuthUserName() != null ? SIPConfig.getAuthUserName() : ((SipURI) uri).getUser();
                defaultCredentials.setAuthUserName(user == null ? SIPConfig.getUserName() : user);
            }
            boolean ccEntryHasSeenTran = false;
            if (ccEntry != null)
                ccEntryHasSeenTran = ccEntry.processResponse(branchID);
            // get a new pass
            if (// we don't have credentials for the
            ccEntry == null || // specified realm
            ((!authHeader.isStale() && ccEntryHasSeenTran))) {
                if (ccEntry == null) {
                    ccEntry = new CredentialsCacheEntry();
                    ccEntry.userCredentials = defaultCredentials;
                }
                // put the returned user name in the properties file
                // so that it appears as a default one next time user is
                // prompted for pass
                SIPConfig.setUserName(ccEntry.userCredentials.getUserName());
            } else // encode and send what we have
            if (ccEntry != null && (!ccEntryHasSeenTran || authHeader.isStale())) {
            }
            // if user canceled or sth else went wrong
            if (ccEntry.userCredentials == null)
                throw new SecurityException("Unable to authenticate with realm " + realm);
            AuthorizationHeader authorization = this.getAuthorization(reoriginatedRequest.getMethod(), reoriginatedRequest.getRequestURI().toString(), reoriginatedRequest.getContent() == null ? "" : reoriginatedRequest.getContent().toString(), authHeader, ccEntry.userCredentials);
            ccEntry.processRequest(retryTran.getBranchId());
            cachedCredentials.cacheEntry(realm, ccEntry);
            reoriginatedRequest.addHeader(authorization);
            // if there was trouble with the user - make sure we fix it
            if (uri.isSipURI()) {
                ((SipURI) uri).setUser(ccEntry.userCredentials.getUserName());
                Address add = from.getAddress();
                add.setURI(uri);
                from.setAddress(add);
                reoriginatedRequest.setHeader(from);
                if (challengedRequest.getMethod().equals(Request.REGISTER)) {
                    ToHeader to = (ToHeader) reoriginatedRequest.getHeader(ToHeader.NAME);
                    add.setURI(uri);
                    to.setAddress(add);
                    reoriginatedRequest.setHeader(to);
                }
                // very ugly but very necessary
                sipManCallback.setCurrentlyUsedURI(uri.toString());
                Log.debug("URI: " + uri.toString());
            }
        // if this is a register - fix to as well
        }
        return retryTran;
    } catch (Exception e) {
        Log.debug("ERRO REG: " + e.toString());
        return null;
    }
}
Also used : Address(javax.sip.address.Address) ClientTransaction(javax.sip.ClientTransaction) Request(javax.sip.message.Request) ListIterator(java.util.ListIterator) SipURI(javax.sip.address.SipURI) URI(javax.sip.address.URI) SipURI(javax.sip.address.SipURI) SipException(javax.sip.SipException) InvalidArgumentException(javax.sip.InvalidArgumentException) ParseException(java.text.ParseException)

Example 15 with ParseException

use of java.text.ParseException in project Openfire by igniterealtime.

the class RegisterProcessing method register.

synchronized void register(String registrarAddress, int registrarPort, String registrarTransport, int expires) throws CommunicationsException {
    try {
        isUnregistering = false;
        // From
        FromHeader fromHeader = sipManCallback.getFromHeader(true);
        Address fromAddress = fromHeader.getAddress();
        sipManCallback.fireRegistering(fromAddress.toString());
        // Request URI
        SipURI requestURI = null;
        try {
            requestURI = sipManCallback.addressFactory.createSipURI(null, registrarAddress);
        } catch (ParseException ex) {
            throw new CommunicationsException("Bad registrar address:" + registrarAddress, ex);
        } catch (NullPointerException ex) {
            // Do not throw an exc, we should rather silently notify the
            // user
            // throw new CommunicationsException("A registrar address was
            // not specified!", ex);
            sipManCallback.fireUnregistered(fromAddress.getURI().toString() + " (registrar not specified)");
            return;
        }
        requestURI.setPort(registrarPort);
        try {
            requestURI.setTransportParam(registrarTransport);
        } catch (ParseException ex) {
            throw new CommunicationsException(registrarTransport + " is not a valid transport!", ex);
        }
        // Call ID Header
        CallIdHeader callIdHeader = sipManCallback.sipProvider.getNewCallId();
        // CSeq Header
        CSeqHeader cSeqHeader = null;
        try {
            cSeqHeader = sipManCallback.headerFactory.createCSeqHeader(1, Request.REGISTER);
        } catch (ParseException ex) {
            // Should never happen
            Log.error("register", ex);
        } catch (InvalidArgumentException ex) {
            // Should never happen
            Log.error("register", ex);
        }
        // To Header
        ToHeader toHeader = null;
        try {
            toHeader = sipManCallback.headerFactory.createToHeader(fromAddress, null);
        } catch (ParseException ex) {
            // throw was missing - reported by Eero Vaarnas
            throw new CommunicationsException("Could not create a To header " + "for address:" + fromHeader.getAddress(), ex);
        }
        // User Agent Header
        UserAgentHeader uaHeader = null;
        ArrayList<String> userAgentList = new ArrayList<String>();
        userAgentList.add(SIPConfig.getStackName());
        try {
            uaHeader = sipManCallback.headerFactory.createUserAgentHeader(userAgentList);
        } catch (ParseException ex) {
            // throw was missing - reported by Eero Vaarnas
            throw new CommunicationsException("Could not create a To header " + "for address:" + fromHeader.getAddress(), ex);
        }
        // Via Headers
        ArrayList viaHeaders = sipManCallback.getLocalViaHeaders();
        // MaxForwardsHeader
        MaxForwardsHeader maxForwardsHeader = sipManCallback.getMaxForwardsHeader();
        // Request
        Request request = null;
        try {
            request = sipManCallback.messageFactory.createRequest(requestURI, Request.REGISTER, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader);
            request.setHeader(uaHeader);
        } catch (ParseException ex) {
            // throw was missing - reported by Eero Vaarnas
            throw new CommunicationsException("Could not create the register request!", ex);
        }
        // Expires Header
        ExpiresHeader expHeader = null;
        for (int retry = 0; retry < 2; retry++) {
            try {
                expHeader = sipManCallback.headerFactory.createExpiresHeader(expires);
            } catch (InvalidArgumentException ex) {
                if (retry == 0) {
                    expires = 3600;
                    continue;
                }
                throw new CommunicationsException("Invalid registrations expiration parameter - " + expires, ex);
            }
        }
        request.addHeader(expHeader);
        // Contact Header should contain IP - bug report - Eero Vaarnas
        ContactHeader contactHeader = sipManCallback.getRegistrationContactHeader();
        request.addHeader(contactHeader);
        // Transaction
        ClientTransaction regTrans = null;
        try {
            regTrans = sipManCallback.sipProvider.getNewClientTransaction(request);
        } catch (TransactionUnavailableException ex) {
            // throw was missing - reported by Eero Vaarnas
            throw new CommunicationsException("Could not create a register transaction!\n" + "Check that the Registrar address is correct!");
        }
        try {
            regTrans.sendRequest();
        }// we sometimes get a null pointer exception here so catch them all
         catch (Exception ex) {
            // throw was missing - reported by Eero Vaarnas
            throw new CommunicationsException("Could not send out the register request!", ex);
        }
        this.registerRequest = request;
    } catch (Exception e) {
        Log.error("register", e);
    }
}
Also used : Address(javax.sip.address.Address) ArrayList(java.util.ArrayList) Request(javax.sip.message.Request) SipURI(javax.sip.address.SipURI) SipSecurityException(org.jivesoftware.openfire.sip.tester.security.SipSecurityException) CommunicationsException(org.jivesoftware.openfire.sip.tester.comm.CommunicationsException) ParseException(java.text.ParseException) ParseException(java.text.ParseException) CommunicationsException(org.jivesoftware.openfire.sip.tester.comm.CommunicationsException)

Aggregations

ParseException (java.text.ParseException)3530 Date (java.util.Date)1381 SimpleDateFormat (java.text.SimpleDateFormat)1296 IOException (java.io.IOException)366 ArrayList (java.util.ArrayList)334 DateFormat (java.text.DateFormat)305 Calendar (java.util.Calendar)288 Test (org.junit.Test)274 HashMap (java.util.HashMap)139 Matcher (java.util.regex.Matcher)99 File (java.io.File)97 GregorianCalendar (java.util.GregorianCalendar)97 Map (java.util.Map)95 List (java.util.List)92 BigDecimal (java.math.BigDecimal)72 Locale (java.util.Locale)68 ParsePosition (java.text.ParsePosition)57 Timestamp (java.sql.Timestamp)55 InputStream (java.io.InputStream)53 DecimalFormat (java.text.DecimalFormat)50