微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.text.MessageFormat的实例源码

项目:ramus    文件JNLPSeasonInternetServlet.java   
private void accept(HttpServletRequest req,HttpServletResponse resp) {
    try {
        String localAddr = req.getLocalAddr();
        Properties properties = EngineFactory.getPropeties();
        if (properties.getProperty("hostname") != null) {
            localAddr = properties.getProperty("hostname");
        }
        String path = "http://" + localAddr + ":" + req.getLocalPort()
                + req.getcontextpath();
        InputStream is = getClass().getResourceAsstream(
                "/com/ramussoft/jnlp/season-internet-client.jnlp");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int r;
        while ((r = is.read()) >= 0)
            out.write(r);
        String string = messageformat.format(new String(out.toByteArray(),"UTF8"),path);
        resp.setContentType("application/x-java-jnlp-file");
        OutputStream o = resp.getoutputStream();
        o.write(string.getBytes("UTF8"));
        o.close();
    } catch (IOException e) {
        e.printstacktrace();
    }

}
项目:pgcodekeeper    文件ModelExporter.java   
private File mkdirObjects(File parentOutDir,String outDirName)
        throws NotDirectoryException,DirectoryException {
    File objectDir = new File(parentOutDir,outDirName);

    if(objectDir.exists()) {
        if(!objectDir.isDirectory()) {
            throw new NotDirectoryException(objectDir.getAbsolutePath());
        }
    } else {
        if(!objectDir.mkdir()) {
            throw new DirectoryException(messageformat.format(
                    "Could not create objects directory: {0}",objectDir.getAbsolutePath()));
        }
    }
    return objectDir;
}
项目:alfresco-remote-api    文件TestRemovePermissions.java   
protected Session getbroWSER_11_Session()
{
    try
    {
        Map<String,String> parameter = new HashMap<String,String>();
        int port = getTestFixture().getJettyComponent().getPort();

        parameter.put(SessionParameter.BINDING_TYPE,BindingType.broWSER.value());
        parameter.put(SessionParameter.broWSER_URL,messageformat.format(broWSE_URL_11,DEFAULT_HOSTNAME,String.valueOf(port)));
        parameter.put(SessionParameter.COOKIES,"true");

        parameter.put(SessionParameter.USER,ADMIN_USER);
        parameter.put(SessionParameter.PASSWORD,ADMIN_PASSWORD);

        SessionFactory sessionFactory = SessionFactoryImpl.newInstance();

        parameter.put(SessionParameter.REPOSITORY_ID,sessionFactory.getRepositories(parameter).get(0).getId());
        return sessionFactory.createSession(parameter);
    }
    catch (Exception ex)
    {
        logger.error(ex);

    }
    return null;
}
项目:Open-DM    文件ConfigurationHelper.java   
public static int getIntegerProperty(String key,int defaultVal) {
    String propertyValue;
    Integer retval;
    propertyValue = getStringProperty(key,null);

    if (propertyValue == null || propertyValue.trim().length() < 1) {
        retval = defaultVal;

    } else {
        try {
            retval = Integer.parseInt(propertyValue);
        } catch (NumberFormatException e) {
            String msg = "Read configuration property {0} = {1},but Could not convert it to type {2}.";
            Object[] objs = new Object[] {
                    key,propertyValue,Integer.class.getName(),};
            LOG.log(Level.WARNING,messageformat.format(msg,objs),e);
            throw e;
        }
    }
    return retval;
}
项目:Transwarp-Sample-Code    文件KerberosWebHDFSConnection2.java   
/**
 * <b>CREATESYMLINK</b>
 *
 * curl -i -X PUT "http://<HOST>:<PORT>/<PATH>?op=CREATESYMLINK
 * &destination=<PATH>[&createParent=<true|false>]"
 *
 * @param srcPath
 * @param destPath
 * @return
 * @throws AuthenticationException
 * @throws IOException
 * @throws MalformedURLException
 */
public String createSymLink(String srcPath,String destPath)
        throws MalformedURLException,IOException,AuthenticationException {
    String resp = null;
    ensureValidToken();

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl),messageformat.format(
                    "/webhdfs/v1/{0}?op=CREATESYMLINK&destination={1}",URLUtil.encodePath(srcPath),URLUtil.encodePath(destPath))),token);
    conn.setRequestMethod("PUT");
    conn.connect();
    resp = result(conn,true);
    conn.disconnect();

    return resp;
}
项目:parabuild-ci    文件FindBugsFrame.java   
public String toString() {
    try {
        BugInstance bugInstance = (BugInstance) getUserObject();
        StringBuffer result = new StringBuffer();

        if (count >= 0) {
            result.append(count);
            result.append(": ");
        }

        if (bugInstance.isExperimental())
            result.append(L10N.getLocalString("msg.exp_txt","EXP: "));

        result.append(fullDescriptionsItem.isSelected() ? bugInstance.getMessage() : bugInstance.toString());

        return result.toString();
    } catch (Exception e) {
        return messageformat.format(L10N.getLocalString("msg.errorformatting_txt","Error formatting message for bug: "),new Object[]{e.toString()});
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件JNDIRealm.java   
/**
 * Set the message format pattern for selecting users in this Realm.
 * This may be one simple pattern,or multiple patterns to be tried,* separated by parentheses. (for example,either "cn={0}",or
 * "(cn={0})(cn={0},o=myorg)" Full LDAP search strings are also supported,* but only the "OR","|" Syntax,so "(|(cn={0})(cn={0},o=myorg))" is
 * also valid. Complex search strings with &,etc are NOT supported.
 *
 * @param userPattern The new user pattern
 */
public void setUserPattern(String userPattern) {

    this.userPattern = userPattern;
    if (userPattern == null)
        userPatternArray = null;
    else {
        userPatternArray = parseUserPatternString(userPattern);
        int len = this.userPatternArray.length;
        userPatternFormatArray = new messageformat[len];
        for (int i=0; i < len; i++) {
            userPatternFormatArray[i] =
                new messageformat(userPatternArray[i]);
        }
    }
}
项目:jwala    文件GroupServiceImpl.java   
@Override
@Transactional
public Group createGroup(final CreateGroupRequest createGroupRequest,final User aCreatingUser) {
    createGroupRequest.validate();
    try {
        groupPersistenceService.getGroup(createGroupRequest.getGroupName());
        String message = messageformat.format("Group Name already exists: {0} ",createGroupRequest.getGroupName());
        LOGGER.error(message);
        throw new EntityExistsException(message);
    } catch (NotFoundException e) {
        LOGGER.debug("No group name conflict,ignoring not found exception for creating group ",e);
    }

    return groupPersistenceService.createGroup(createGroupRequest);
}
项目:ramus    文件ReportEditorView.java   
protected String getHTMLText() {
    String page;
    try {
        HashMap<String,Object> map = new HashMap<String,Object>();
        Query query = queryView.getQuery();
        if (query != null)
            map.put("query",query);
        page = ((ReportQuery) framework.getEngine()).getHTMLReport(element,map);
    } catch (Exception e1) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        PrintStream s = new PrintStream(stream);
        e1.printstacktrace();
        if (e1 instanceof DataException)
            s.println(((DataException) e1)
                    .getMessage(new messageformatter() {

                        @Override
                        public String getString(String key,Object[] arguments) {
                            return messageformat.format(
                                    ReportResourceManager.getString(key),arguments);
                        }
                    }));
        else {
            e1.printstacktrace(s);
        }

        s.flush();

        page = new String(stream.toByteArray());
    }
    return page;
}
项目:incubator-servicecomb-java-chassis    文件TracingConfiguration.java   
@Bean
Sender sender(DynamicProperties dynamicProperties) {
  apiVersion = dynamicProperties.getStringProperty(CONfig_TRACING_COLLECTOR_API_VERSION,CONfig_TRACING_COLLECTOR_API_V2).toLowerCase();
  // use default value if the user set value is invalid
  if (apiVersion.compareto(CONfig_TRACING_COLLECTOR_API_V1) != 0){
    apiVersion = CONfig_TRACING_COLLECTOR_API_V2;
  }

  String path = messageformat.format(CONfig_TRACING_COLLECTOR_PATH,apiVersion);
  return OkHttpSender.create(
      dynamicProperties.getStringProperty(
          CONfig_TRACING_COLLECTOR_ADDRESS,DEFAULT_TRACING_COLLECTOR_ADDRESS)
          .trim()
          .replaceAll("/+$","")
          .concat(path));
}
项目:cloud-ariba-partner-flow-extension-ext    文件EcmServiceProvider.java   
private static EcmService initEcmService() {
    LOGGER.debug(DEBUG_INITIALIZING_ECM_SERVICE);

    EcmService ecmService;
    try {
        InitialContext initialContext = new InitialContext();
        ecmService = (EcmService) initialContext.lookup(ECM_SERVICE_NAME);
    } catch (NamingException e) {
        String errorMessage = messageformat.format(ERROR_LOOKING_UP_THE_ECM_SERVICE_Failed,ECM_SERVICE_NAME);
        LOGGER.error(errorMessage,e);
        throw new RuntimeException(errorMessage,e);
    }

    LOGGER.debug(DEBUG_ECM_SERVICE_INITIALIZED);
    return ecmService;
}
项目:CalendarFX    文件SearchResultViewSkin.java   
private String getTimeText(Entry<?> entry) {
    if (entry.isFullDay()) {
        return "all-day"; //$NON-NLS-1$
    }

    LocalDate startDate = entry.getStartDate();
    LocalDate endDate = entry.getEndDate();

    String text;
    if (startDate.equals(endDate)) {
        text = messageformat.format(Messages.getString("SearchResultViewSkin.FROM_UNTIL"),//$NON-NLS-1$
                timeFormatter.format(entry.getStartTime()),timeFormatter.format(entry.getEndTime()));
    } else {
        text = messageformat.format(Messages.getString("SearchResultViewSkin.FROM_UNTIL_WITH_DATE"),dateFormatter.format(entry.getStartDate()),timeFormatter.format(entry.getEndTime()),dateFormatter.format(entry.getEndDate()));
    }

    return text;
}
项目:hepek-classycle    文件XMLAtomicVertexRenderer.java   
/**
 * Renderes the specified vertex. It is assumed that the vertex attributes are of the type
 * {@link classycle.ClassAttributes}.
 *
 * @return the rendered vertex.
 */
@Override
public String render(AtomicVertex vertex,StrongComponent cycle,int layerIndex) {
    final StringBuilder result = new StringBuilder();
    result.append(getVertexRenderer().render(vertex,cycle,layerIndex));
    final messageformat format = new messageformat(
            "      <" + getRefElement() + " name=\"{0}\"" + " type=\"{1}\"/>\n");
    final String[] values = new String[2];
    for (int i = 0,n = vertex.getNumberOfIncomingArcs(); i < n; i++) {
        values[0] = ((NameAttributes) vertex.getTailVertex(i).getAttributes()).getName();
        values[1] = "usedBy";
        result.append(format.format(values));
    }
    for (int i = 0,n = vertex.getNumberOfOutgoingArcs(); i < n; i++) {
        values[0] = ((NameAttributes) vertex.getHeadVertex(i).getAttributes()).getName();
        values[1] = ((AtomicVertex) vertex.getHeadVertex(i)).isGraphVertex() ? "usesInternal" : "usesExternal";
        result.append(format.format(values));
    }
    result.append("    </").append(getElement()).append(">\n");
    return result.toString();
}
项目:incubator-netbeans    文件OptionsExportModel.java   
/** Adds build.info file with product,os,java version to zip file. */
private static void createProductInfo(ZipOutputStream out) throws IOException {
    String productVersion = messageformat.format(
            NbBundle.getBundle("org.netbeans.core.startup.Bundle").getString("currentVersion"),//NOI18N
            new Object[]{System.getProperty("netbeans.buildnumber")}); //NOI18N
    String os = System.getProperty("os.name","unkNown") + "," + //NOI18N
            System.getProperty("os.version"," + //NOI18N
            System.getProperty("os.arch","unkNown"); //NOI18N
    String java = System.getProperty("java.version"," + //NOI18N
            System.getProperty("java.vm.name"," + //NOI18N
            System.getProperty("java.vm.version",""); //NOI18N
    out.putNextEntry(new ZipEntry("build.info"));  //NOI18N
    PrintWriter writer = new PrintWriter(out);
    writer.println("NetbeansBuildnumber=" + System.getProperty("netbeans.buildnumber")); //NOI18N
    writer.println("ProductVersion=" + productVersion); //NOI18N
    writer.println("OS=" + os); //NOI18N
    writer.println("Java=" + java); //NOI18Nv
    writer.println("Userdir=" + System.getProperty("netbeans.user")); //NOI18N
    writer.flush();
    // Complete the entry
    out.closeEntry();
}
项目:SKIL_Examples    文件Model.java   
public JSONObject addModel(String name,String fileLocation,int scale,String uri) {
    JSONObject model = new JSONObject();

    try {
        List<String> uriList = new ArrayList<String>();
        uriList.add(uri);

        model =
                Unirest.post(messageformat.format("http://{0}:{1}/deployment/{2}/model",host,port,deploymentID))
                        .header("accept","application/json")
                        .header("Content-Type","application/json")
                        .body(new JSONObject()
                                .put("name",name)
                                .put("modelType","model")
                                .put("fileLocation",fileLocation)
                                .put("scale",scale)
                                .put("uri",uriList)
                                .toString())
                        .asJson()
                        .getBody().getobject();
    } catch (UnirestException e) {
        e.printstacktrace();
    }

    return model;
}
项目:Equella    文件Version.java   
public WebVersion getDeployedVersion()
{
    WebVersion version = new WebVersion();
    File versionFile = new File(getVersionPropertiesDirectory(),"version.properties");
    try( FileInputStream in = new FileInputStream(versionFile) )
    {
        Properties p = new Properties();
        p.load(in);
        version.setdisplayName(p.getProperty("version.display"));
        version.setMmr(p.getProperty("version.mmr"));
        version.setFilename(messageformat.format("tle-upgrade-{0} ({1}).zip",p.getProperty("version.mmr"),p.getProperty("version.display")));
    }
    catch( IOException ex )
    {
        version.setdisplayName(Utils.UNKNowN_VERSION);
    }
    return version;
}
项目:pgcodekeeper    文件IPgObjectPage.java   
static IFolder createSchema(String name,boolean open,IProject project) throws CoreException {
    IFolder projectFolder = project.getFolder(DbObjType.SCHEMA.name());
    if (!projectFolder.exists()) {
        projectFolder.create(false,true,null);
    }
    IFolder schemaFolder = projectFolder.getFolder(name);
    if (!schemaFolder.exists()) {
        schemaFolder.create(false,null);
    }
    IFile file = projectFolder.getFile(name + POSTFIX);
    if (!file.exists()) {
        StringBuilder sb = new StringBuilder();
        sb.append(messageformat.format(PATTERN,DbObjType.SCHEMA,name));
        sb.append(messageformat.format(OWNER_TO,name));
        file.create(new ByteArrayInputStream(sb.toString().getBytes()),false,null);
    }
    if (open) {
        openFileInEditor(file);
    }
    return schemaFolder;
}
项目:hadoop-oss    文件TestJarFinder.java   
private static void delete(File file) throws IOException {
  if (file.getAbsolutePath().length() < 5) {
    throw new IllegalArgumentException(
      messageformat.format("Path [{0}] is too short,not deleting",file.getAbsolutePath()));
  }
  if (file.exists()) {
    if (file.isDirectory()) {
      File[] children = file.listFiles();
      if (children != null) {
        for (File child : children) {
          delete(child);
        }
      }
    }
    if (!file.delete()) {
      throw new RuntimeException(
        messageformat.format("Could not delete path [{0}]",file.getAbsolutePath()));
    }
  }
}
项目:jwala    文件JvmServiceImpl.java   
@Override
public Jvm generateAndDeployFile(String jvmName,String fileName,User user) {
    Jvm jvm = getJvm(jvmName);
    // only one at a time per jvm
    binarydistributionLockManager.writeLock(jvmName + "-" + jvm.getId().getId().toString());
    try {
        ResourceIdentifier resourceIdentifier = new ResourceIdentifier.Builder()
                .setResourceName(fileName)
                .setJvmName(jvmName)
                .build();
        checkJvmStateBeforeDeploy(jvm,resourceIdentifier);

        resourceService.validateSingleResourceForGeneration(resourceIdentifier);
        resourceService.generateAndDeployFile(resourceIdentifier,jvm.getJvmName(),fileName,jvm.getHostName());
    } catch (IOException e) {
        String errorMsg = messageformat.format("Failed to retrieve Meta data when generating and deploying file {0} for JVM {1}",jvmName);
        LOGGER.error(errorMsg,e);
        throw new JvmServiceException(errorMsg);
    } finally {
        binarydistributionLockManager.writeUnlock(jvmName + "-" + jvm.getId().getId().toString());
        LOGGER.debug("End generateAndDeployFile for {} by user {}",jvmName,user.getId());
    }
    return jvm;
}
项目:SKIL_Examples    文件Model.java   
public JSONObject deleteModel(int modelID) {
    JSONObject model = new JSONObject();

    try {
        model =
                Unirest.delete(messageformat.format("http://{0}:{1}/deployment/{2}/model/{3}",deploymentID,modelID))
                        .header("accept","application/json")
                        .asJson()
                        .getBody().getobject();
    } catch (UnirestException e) {
        e.printstacktrace();
    }

    return model;
}
项目:task-app    文件TaskAppServiceImpl.java   
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Long createTask(String type,String name,String actor,String creator) {
    JmdTask task = new JmdTask();
    task.setType(type);
    task.setCreator(creator);
    task.setCreated(taskDao.getCurrentDate());
    task.setActor(actor);
    task.setName(name);
    task.setNameScdf(ScDf.toScDf(name));
    task.setStatus(TaskStatus.BOOKED.name());
    task.setInterruptEnabled(true);
    task.setInterruptFlag(false);
    task.setStopEnabled(true);
    task.setStopFlag(false);
    task.setKillFlag(false);
    task.setTotalStep(Integer.MAX_VALUE);
    task.setActualStep(0);
    task.setLastUpdate(task.getCreated());
    long taskId = taskDao.addTask(task);
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(messageformat.format("Task with id {0} created.",taskId));
    }
    return taskId;
}
项目:monarch    文件LauncherLifecycleCommandsDUnitTest.java   
@Test
public void test004StartServerFailsFastOnMissingGemFirePropertiesFile() throws IOException {
  String gemfirePropertiesFile = "/path/to/missing/gemfire.properties";

  CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_SERVER);

  String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
  final File workingDirectory = temporaryFolder.newFolder(pathName);

  command.addOption(CliStrings.START_SERVER__NAME,pathName);
  command.addOption(CliStrings.START_SERVER__DIR,workingDirectory.getCanonicalPath());
  command.addOption(CliStrings.START_SERVER__PROPERTIES,gemfirePropertiesFile);

  CommandResult result = executeCommand(command.toString());

  assertNotNull(result);
  assertEquals(Result.Status.ERROR,result.getStatus());

  String resultString = toString(result);

  assertTrue(resultString,resultString
          .contains(messageformat.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE,StringUtils.EMPTY_STRING,gemfirePropertiesFile)));
}
项目:Equella    文件ZookeeperServiceImpl.java   
@postconstruct
private void setupNodeId()
{
    String randomUuid = UUID.randomUUID().toString();
    if( Check.isEmpty(zooKeeperNodeId) )
    {
        try
        {
            String hostname = InetAddress.getLocalHost().getHostName();
            zooKeeperNodeId = !Check.isEmpty(hostname) ? messageformat.format("{0}-{1}",hostname,randomUuid)
                : randomUuid;
        }
        catch( UnkNownHostException e )
        {
            LOGGER.warn("Unable to retrieve hostname to generate node ID. Using random ID");
            zooKeeperNodeId = randomUuid;
        }
    }
    else
    {
        zooKeeperNodeId = messageformat.format("{0}-{1}",zooKeeperNodeId,randomUuid);
    }
}
项目:openjdk-jdk10    文件SchemaWriter.java   
public void attributeUse( XSAttributeUse use ) {
    XSAttributeDecl decl = use.getDecl();

    String additionalAtts="";

    if(use.isrequired())
        additionalAtts += " use=\"required\"";
    if(use.getFixedValue()!=null && use.getDecl().getFixedValue()==null)
        additionalAtts += " fixed=\""+use.getFixedValue()+'\"';
    if(use.getDefaultValue()!=null && use.getDecl().getDefaultValue()==null)
        additionalAtts += " default=\""+use.getDefaultValue()+'\"';

    if(decl.isLocal()) {
        // this is anonymous attribute use
        dump(decl,additionalAtts);
    } else {
        // reference to a global one
        println(messageformat.format("<attribute ref=\"'{'{0}'}'{1}{2}\"/>",decl.getTargetNamespace(),decl.getName(),additionalAtts));
    }
}
项目:incubator-netbeans    文件LogHandler.java   
@Override
public void publish(LogRecord record) {
    if(!done) {
        String message = record.getMessage();
        if(message == null) {
            return;
        }
        message = messageformat.format(message,record.getParameters());
        boolean intercepted = false;
        switch (compare) {
            case STARTS_WITH :
                intercepted = message.startsWith(messagetoWaitFor);
                break;
            case ENDS_WITH :
                intercepted = message.endsWith(messagetoWaitFor);
                break;
            default:
                throw new IllegalStateException("wrong value " + compare);
        }
        if(intercepted) {
            interceptedCount++;
            interceptedMessage = message;
        }
        done = intercepted && interceptedCount >= expectedCount;
    }
}
项目:cyberduck    文件RenameExistingFilter.java   
/**
 * Rename existing file on server if there is a conflict.
 */
@Override
public void apply(final Path file,final Local local,final TransferStatus status,final ProgressListener listener) throws BackgroundException {
    // Rename existing file before putting new file in place
    if(status.isExists()) {
        Path rename;
        do {
            final String proposal = messageformat.format(PreferencesFactory.get().getProperty("queue.upload.file.rename.format"),FilenameUtils.getBaseName(file.getName()),UserDateFormatterFactory.get().getMediumFormat(System.currentTimeMillis(),false).replace(Path.DELIMITER,'-').replace(':','-'),StringUtils.isNotBlank(file.getExtension()) ? String.format(".%s",file.getExtension()) : StringUtils.EMPTY);
            rename = new Path(file.getParent(),proposal,file.getType());
        }
        while(find.find(rename));
        if(log.isInfoEnabled()) {
            log.info(String.format("Rename existing file %s to %s",file,rename));
        }
        move.move(file,rename,new TransferStatus().exists(false),new Delete.disabledCallback(),new disabledConnectionCallback());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Clear exist flag for file %s",file));
        }
        status.setExists(false);
    }
    super.apply(file,local,status,listener);
}
项目:saluki    文件MapTypeBuilder.java   
@Override
public TypeDeFinition build(Type type,Class<?> clazz,Map<Class<?>,TypeDeFinition> typeCache) {
    if (!(type instanceof ParameterizedType)) {
        throw new IllegalArgumentException(messageformat.format("[Jaket] Unexpected type {0}.",new Object[]{type}));
    }

    ParameterizedType parameterizedType = (ParameterizedType) type;
    Type[] actualTypeArgs = parameterizedType.getActualTypeArguments();
    if (actualTypeArgs == null || actualTypeArgs.length != 2) {
        throw new IllegalArgumentException(messageformat.format(
                "[Jaket] Map type [{0}] with unexpected amount of arguments [{1}]." + actualTypeArgs,new Object[] {
                        type,actualTypeArgs }));
    }

    for (Type actualType : actualTypeArgs) {
        if (actualType instanceof ParameterizedType) {
            // nested collection or map.
            Class<?> rawType = (Class<?>) ((ParameterizedType) actualType).getRawType();
            JaketTypeBuilder.build(actualType,rawType,typeCache);
        } else if (actualType instanceof Class<?>) {
            Class<?> actualClass = (Class<?>) actualType;
            if (actualClass.isArray() || actualClass.isEnum()) {
                JaketTypeBuilder.build(null,actualClass,typeCache);
            } else {
                DefaultTypeBuilder.build(actualClass,typeCache);
            }
        }
    }

    TypeDeFinition td = new TypeDeFinition(type.toString());
    return td;
}
项目:open-rmbt    文件RMBTLoopService.java   
private void setNotificationText(NotificationCompat.Builder builder)
{
    final Resources res = getResources();

    final long Now = SystemClock.elapsedRealtime();
    final long lastTestDelta = loopModeResults.getLastTestTime() == 0 ? 0 : Now - loopModeResults.getLastTestTime();

    final String elapsedtimeString = LoopModeTriggerItem.formatSeconds(Math.round(lastTestDelta / 1000),1);

    final CharSequence textTemplate = res.getText(R.string.loop_notification_text_without_stop);
    final CharSequence text = messageformat.format(textTemplate.toString(),loopModeResults.getNumberOfTests(),elapsedtimeString,Math.round(loopModeResults.getLastdistance()));
    builder.setContentText(text);

    if (bigTextStyle == null)
    {
        bigTextStyle = (new NotificationCompat.BigTextStyle());
        builder.setStyle(bigTextStyle);
    }

    bigTextStyle.bigText(text);
}
项目:asura    文件LoggingJobHistoryPlugin.java   
/** 
 * @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext,JobExecutionException)
 */
public void jobWasExecuted(JobExecutionContext context,JobExecutionException jobException) {

    Trigger trigger = context.getTrigger();

    Object[] args = null;

    if (jobException != null) {
        if (!getLog().isWarnEnabled()) {
            return;
        } 

        String errMsg = jobException.getMessage();
        args = 
            new Object[] {
                context.getJobDetail().getName(),context.getJobDetail().getGroup(),new java.util.Date(),trigger.getName(),trigger.getGroup(),trigger.getPrevIoUsFireTime(),trigger.getNextFireTime(),new Integer(context.getRefireCount()),errMsg
            };

        getLog().warn(messageformat.format(getJobFailedMessage(),args),jobException); 
    } else {
        if (!getLog().isInfoEnabled()) {
            return;
        } 

        String result = String.valueOf(context.getResult());
        args =
            new Object[] {
                context.getJobDetail().getName(),result
            };

        getLog().info(messageformat.format(getJobSuccessMessage(),args));
    }
}
项目:neoscada    文件DefaultMavenMapping.java   
private List<MavenReference> fromValue ( final IInstallableunit iu,final String value ) throws Exception
{
    final String[] segs = value.split ( "," );

    final List<MavenReference> result = new ArrayList<> ( segs.length );

    for ( final String seg : segs )
    {
        final String[] toks = seg.split ( "\\:" );
        if ( toks.length == 3 )
        {
            final String version = messageformat.format ( toks[2],getSegments ( iu.getVersion () ) );
            result.add ( new MavenReference ( toks[0],toks[1],version ) );
        }
        else if ( toks.length == 2 )
        {
            // automatic version
            result.add ( new MavenReference ( toks[0],makeVersion ( iu,false ) ) );
        }
        else
        {
            throw new IllegalArgumentException ( String.format ( "Maven reference has invalid Syntax: %s",value ) );
        }
    }
    return result;
}
项目:Transwarp-Sample-Code    文件KerberosWebHDFSConnection2.java   
/**
 * <b>GETFILESTATUS</b>
 *
 * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=GETFILESTATUS"
 *
 * @param path
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String getFileStatus(String path) throws MalformedURLException,AuthenticationException {
    ensureValidToken();

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl),messageformat.format(
                    "/webhdfs/v1/{0}?op=GETFILESTATUS",URLUtil.encodePath(path))),token);
    conn.setRequestMethod("GET");
    conn.connect();
    String resp = result(conn,true);
    conn.disconnect();

    return resp;
}
项目:ProjectAres    文件MessageTemplate.java   
/**
 * Create a localized {@link MessageTemplate} from the given message key.
 */
public MessageTemplate fromKey(String key) {
    if(!translator.hasKey(key)) {
        throw new IllegalArgumentException("Missing translation key '" + key + "'");
    }
    return new MessageTemplate() {
        @Override
        public boolean isLocalized() {
            return true;
        }

        @Override
        public messageformat format(Locale locale) {
            return translator.pattern(key,locale).get();
        }

        @Override
        public String toString() {
            return MessageTemplate.class.getSimpleName() + "{key=" + key + "}";
        }
    };
}
项目:cyberduck    文件S3UrlProvider.java   
/**
 * Properly URI encode and prepend the bucket name.
 *
 * @param scheme Protocol
 * @return URL to be displayed in browser
 */
protected DescriptiveUrl toUrl(final Path file,final Scheme scheme) {
    final StringBuilder url = new StringBuilder(scheme.name());
    url.append("://");
    if(file.isRoot()) {
        url.append(session.getHost().getHostname());
    }
    else {
        final String hostname = this.getHostnameForContainer(containerService.getContainer(file));
        if(hostname.startsWith(containerService.getContainer(file).getName())) {
            url.append(hostname);
            if(!containerService.isContainer(file)) {
                url.append(Path.DELIMITER);
                url.append(URIEncoder.encode(containerService.getKey(file)));
            }
        }
        else {
            url.append(session.getHost().getHostname());
            url.append(URIEncoder.encode(file.getAbsolute()));
        }
    }
    return new DescriptiveUrl(URI.create(url.toString()),DescriptiveUrl.Type.http,messageformat.format(LocaleFactory.localizedString("{0} URL"),scheme.name().toupperCase(Locale.ROOT)));
}
项目:rapidminer    文件I18N.java   
/**
 * Returns a message if found or the key if not found. Arguments <b>can</b> be specified which
 * will be used to format the String. In the {@link ResourceBundle} the String '{0}' (without ')
 * will be replaced by the first argument,'{1}' with the second and so on.
 *
 * Catches the exception thrown by ResourceBundle in the latter case.
 **/
public static String getMessage(ResourceBundle bundle,String key,Object... arguments) {
    try {

        if (arguments == null || arguments.length == 0) {
            return bundle.getString(key);
        } else {
            String message = bundle.getString(key);
            if (message != null) {
                return messageformat.format(message,arguments);
            } else {
                return key;
            }
        }

    } catch (MissingResourceException e) {
        LogService.getRoot().log(Level.FINE,"com.rapidminer.tools.I18N.missing_key",key);
        return key;
    }
}
项目:vxrifa    文件PublisherGenerator.java   
PublisherGenerator generateInitializing() {

        tsb = typespec.classBuilder(messageformat.format("{0}{1}",interfaceElement.getSimpleName(),VXRIFA_PUBLISHER_SUFFIX)).addModifiers(Modifier.PUBLIC);

        tsb.addSuperinterface(TypeName.get(interfaceElement.asType()));

        vertxField = FieldSpec.builder(io.vertx.core.Vertx.class,"vertx",Modifier.PRIVATE,Modifier.FINAL).build();
        tsb.addField(vertxField);

        eventBusAddressField = FieldSpec.builder(java.lang.String.class,"eventBusAddress",Modifier.FINAL).build();
        tsb.addField(eventBusAddressField);

        tsb.addMethod(
                MethodSpec.constructorBuilder()
                        .addModifiers(Modifier.PUBLIC)
                        .addParameter(io.vertx.core.Vertx.class,vertxField.name)
                        .addStatement("this.$N = $N",vertxField,vertxField)
                        .addStatement("this.$N = $S",eventBusAddressField,interfaceElement.getQualifiedname().toString())
                        .build()
        );

        tsb.addMethod(
                MethodSpec.constructorBuilder()
                        .addModifiers(Modifier.PUBLIC)
                        .addParameter(io.vertx.core.Vertx.class,vertxField.name)
                        .addParameter(java.lang.String.class,eventBusAddressField.name)
                        .addStatement("this.$N = $N",vertxField)
                        .addStatement("this.$N = $N",eventBusAddressField)
                        .build()
        );

        return this;

    }
项目:cf-mta-deploy-service    文件GitRepoCloner.java   
public void cloneRepo(final String gitUri,final Path repoDir) throws Invalidremoteexception,GitAPIException,IOException {
    if (Files.exists(repoDir)) {
        LOGGER.debug("Deleting left-over repo dir" + repoDir.toAbsolutePath().toString());
        com.sap.cloud.lm.sl.cf.core.util.FileUtils.deleteDirectory(repoDir);
    }

    configureGitSslValidation();
    if (shoudlUsetoken(gitServiceUrlString,gitUri)) {
        cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName,token));
    }
    if (refName != null && !refName.isEmpty()) {
        String fullRefName = refName.startsWith("refs/") ? refName : "refs/heads/" + refName;
        cloneCommand.setBranchesToClone(Arrays.asList(new String[] { fullRefName }));
        cloneCommand.setBranch(fullRefName);
    }
    cloneCommand.setTimeout(290);
    cloneCommand.setDirectory(repoDir.toAbsolutePath().toFile());
    cloneCommand.setURI(gitUri);
    LOGGER.debug(
        messageformat.format("cloning repo with url {0} in repo dir {1} ref '{2}'",gitUri,repoDir.toAbsolutePath().toString()));
    try (Git callInstance = cloneCommand.call()) {
        Repository repo = callInstance.getRepository();
        repo.close();
    } catch (TransportException e) {
        Throwable cause1 = e.getCause();
        if (cause1 != null && cause1.getCause() instanceof SSLHandshakeException) {
            throw new SLException(cause1.getCause(),"Failed to establish ssl connection"); // NOSONAR
        }
        throw e;
    }
}
项目:incubator-netbeans    文件copyClassesRefactoringPlugin.java   
@Override
public Problem fastCheckParameters() {
    URL target = refactoring.getTarget().lookup(URL.class);
    try {
        target.toURI();
    } catch (URISyntaxException ex) {
        return createProblem(null,NbBundle.getMessage(copyClassesRefactoringPlugin.class,"ERR_InvalidPackage",RefactoringUtils.getPackageName(target)));
    }
    FileObject fo = target != null ? URLMapper.findFileObject(target) : null;
    if (fo == null) {
        return createProblem(null,"ERR_TargetFolderNotSet"));
    }
    if (!JavaRefactoringUtils.isOnSourceClasspath(fo)) {
        return createProblem(null,"ERR_TargetFolderNotJavaPackage"));
    }
    String targetPackageName = RefactoringUtils.getPackageName(target);
    if (!RefactoringUtils.isValidPackageName(targetPackageName)) {
        String msg = new messageformat(NbBundle.getMessage(copyClassesRefactoringPlugin.class,"ERR_InvalidPackage")).format(
                new Object[]{targetPackageName});
        return createProblem(null,msg);
    }
    Collection<? extends FileObject> sources = refactoring.getRefactoringSource().lookupAll(FileObject.class);
    Problem p = null;
    for (FileObject fileObject : sources) {
        if (fo.getFileObject(fileObject.getName(),fileObject.getExt()) != null) {
            p = createProblem(p,"ERR_ClassesTocopyClashes"));
            break;
        }
    }
    return p;
}
项目:cyberduck    文件distributionUrlProvider.java   
/**
 * @param file File in origin container
 * @return CNAME to distribution
 */
private List<DescriptiveUrl> toCnameUrl(final Path file) {
    final List<DescriptiveUrl> urls = new ArrayList<DescriptiveUrl>();
    for(String cname : distribution.getCNAMEs()) {
        final StringBuilder b = new StringBuilder();
        b.append(String.format("%s://%s",distribution.getmethod().getScheme(),cname)).append(distribution.getmethod().getContext());
        if(StringUtils.isNotEmpty(containerService.getKey(file))) {
            b.append(Path.DELIMITER).append(URIEncoder.encode(containerService.getKey(file)));
        }
        urls.add(new DescriptiveUrl(URI.create(b.toString()).normalize(),DescriptiveUrl.Type.cname,LocaleFactory.localizedString(distribution.getmethod().toString(),"S3"))));
    }
    return urls;
}
项目:aws-photosharing-example    文件Share.java   
@Transient
public String getShareUrl() {
    if (getAlbum() != null)
        return messageformat.format(Configuration.SHARE_ALBUM_PUBLIC_URL_FORMAT.toString(),getHash());
    else
        return messageformat.format(Configuration.SHARE_MEDIA_PUBLIC_URL_FORMAT.toString(),getHash());
}
项目:otter-G    文件MessageDumper.java   
public static String dumpMessageInfo(Message<EventData> message,String startPosition,String endPosition,int total) {
    Date Now = new Date();
    SimpleDateFormat format = new SimpleDateFormat(TIMESTAMP_FORMAT);
    int normal = message.getDatas().size();
    return messageformat.format(context_format,String.valueOf(message.getId()),total,normal,total - normal,format.format(Now),startPosition,endPosition);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。